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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const page = parseInt(searchParams.get('page') || '1')
    const limit = parseInt(searchParams.get('limit') || '20')
    const status = searchParams.get('status')
    const userId = searchParams.get('userId')
    const planId = searchParams.get('planId')
    const areaId = searchParams.get('areaId')

    const where: Record<string, unknown> = {}

    if (status) where.status = status
    if (userId) where.userId = userId
    if (planId) where.planId = planId
    if (areaId) {
      where.plan = { areaId }
    }

    const [subscriptions, total] = await Promise.all([
      db.subscription.findMany({
        where,
        include: {
          user: { select: { id: true, name: true, email: true, phone: true, status: true } },
          plan: { include: { area: true } },
          _count: { select: { invoices: true } },
        },
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * limit,
        take: limit,
      }),
      db.subscription.count({ where }),
    ])

    return NextResponse.json({
      success: true,
      data: {
        subscriptions,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit),
        },
      },
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { userId, planId, startDate, autoRenew } = body

    if (!userId || !planId) {
      return NextResponse.json(
        { success: false, error: 'userId and planId are required' },
        { status: 400 }
      )
    }

    const plan = await db.plan.findUnique({ where: { id: planId } })
    if (!plan) {
      return NextResponse.json(
        { success: false, error: 'Plan not found' },
        { status: 404 }
      )
    }

    const user = await db.user.findUnique({ where: { id: userId } })
    if (!user) {
      return NextResponse.json(
        { success: false, error: 'User not found' },
        { status: 404 }
      )
    }

    const start = startDate ? new Date(startDate) : new Date()
    const expiry = new Date(start.getTime() + plan.duration * 24 * 60 * 60 * 1000)

    const subscription = await db.subscription.create({
      data: {
        userId,
        planId,
        startDate: start,
        expiryDate: expiry,
        status: 'ACTIVE',
        autoRenew: autoRenew || false,
      },
      include: {
        user: { select: { id: true, name: true, email: true } },
        plan: true,
      },
    })

    // Update user status to active
    await db.user.update({
      where: { id: userId },
      data: { status: 'ACTIVE' },
    })

    return NextResponse.json({ success: true, data: subscription }, { status: 201 })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
