import { db } from '@/lib/db'
import { NextRequest, NextResponse } from 'next/server'

export async function POST(_request: NextRequest) {
  try {
    const now = new Date()

    // Find all active subscriptions that have expired
    const expiredSubscriptions = await db.subscription.findMany({
      where: {
        status: 'ACTIVE',
        expiryDate: { lt: now },
      },
      include: {
        user: true,
        plan: true,
      },
    })

    const results = {
      processed: 0,
      expired: 0,
      errors: [] as string[],
      details: [] as Array<{
        subscriptionId: string
        userId: string
        userName: string
        planName: string
        expiryDate: string
      }>,
    }

    for (const sub of expiredSubscriptions) {
      try {
        // Check if user has another active subscription
        const otherActiveSubs = await db.subscription.count({
          where: {
            userId: sub.userId,
            status: 'ACTIVE',
            id: { not: sub.id },
            expiryDate: { gte: now },
          },
        })

        if (otherActiveSubs === 0) {
          // Expire the subscription
          await db.subscription.update({
            where: { id: sub.id },
            data: { status: 'EXPIRED' },
          })

          // Mark user as expired
          await db.user.update({
            where: { id: sub.userId },
            data: { status: 'EXPIRED' },
          })

          results.expired++
          results.details.push({
            subscriptionId: sub.id,
            userId: sub.userId,
            userName: sub.user.name,
            planName: sub.plan.name,
            expiryDate: sub.expiryDate.toISOString(),
          })
        }

        results.processed++
      } catch (err: unknown) {
        const errorMessage = err instanceof Error ? err.message : 'Unknown error'
        results.errors.push(`Subscription ${sub.id}: ${errorMessage}`)
      }
    }

    return NextResponse.json({
      success: true,
      data: results,
      message: `Processed ${results.processed} subscriptions, ${results.expired} expired`,
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
