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

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params

    const subscription = await db.subscription.findUnique({
      where: { id },
      include: {
        user: { select: { id: true, name: true, email: true, phone: true, status: true, area: true } },
        plan: { include: { area: true } },
        invoices: { orderBy: { createdAt: 'desc' } },
      },
    })

    if (!subscription) {
      return NextResponse.json(
        { success: false, error: 'Subscription not found' },
        { status: 404 }
      )
    }

    return NextResponse.json({ success: true, data: subscription })
  } 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 PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const body = await request.json()

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

    const { createdAt, updatedAt, user, plan, invoices, ...updateData } = body as Record<string, unknown>

    // If plan is being changed, recalculate expiry
    if (updateData.planId && updateData.planId !== existing.planId) {
      const newPlan = await db.plan.findUnique({ where: { id: updateData.planId as string } })
      if (newPlan) {
        const startDate = updateData.startDate ? new Date(updateData.startDate as string) : existing.startDate
        updateData.expiryDate = new Date(startDate.getTime() + newPlan.duration * 24 * 60 * 60 * 1000)
      }
    }

    const subscription = await db.subscription.update({
      where: { id },
      data: updateData,
      include: {
        user: { select: { id: true, name: true, email: true } },
        plan: true,
      },
    })

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