import { router, protectedProcedure } from '../trpc';
import { db } from '@crafted/database';
import { stripe } from '@crafted/payments';

export const subscriptionRouter = router({
  getMySubscription: protectedProcedure.query(async ({ ctx }) => {
    const subscription = await db.subscription.findFirst({
      where: {
        userId: ctx.userId,
        status: {
          in: ['active', 'trialing'],
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    return subscription;
  }),

  getAll: protectedProcedure.query(async ({ ctx }) => {
    const subscriptions = await db.subscription.findMany({
      where: {
        userId: ctx.userId,
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    return subscriptions;
  }),

  cancel: protectedProcedure.mutation(async ({ ctx }) => {
    const subscription = await db.subscription.findFirst({
      where: {
        userId: ctx.userId,
        status: 'active',
      },
    });

    if (!subscription) {
      throw new Error('No active subscription found');
    }

    await stripe.subscriptions.update(subscription.stripeSubscriptionId, {
      cancel_at_period_end: true,
    });

    await db.subscription.update({
      where: {
        id: subscription.id,
      },
      data: {
        cancelAtPeriodEnd: true,
      },
    });

    return { success: true };
  }),

  reactivate: protectedProcedure.mutation(async ({ ctx }) => {
    const subscription = await db.subscription.findFirst({
      where: {
        userId: ctx.userId,
        cancelAtPeriodEnd: true,
      },
    });

    if (!subscription) {
      throw new Error('No subscription to reactivate');
    }

    await stripe.subscriptions.update(subscription.stripeSubscriptionId, {
      cancel_at_period_end: false,
    });

    await db.subscription.update({
      where: {
        id: subscription.id,
      },
      data: {
        cancelAtPeriodEnd: false,
      },
    });

    return { success: true };
  }),
});
