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 invoice = await db.invoice.findUnique({
      where: { id },
      include: {
        user: { select: { id: true, name: true, email: true, phone: true, address: true, area: true } },
        subscription: { include: { plan: true } },
        payments: { orderBy: { createdAt: 'desc' } },
      },
    })

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

    return NextResponse.json({ success: true, data: invoice })
  } 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.invoice.findUnique({ where: { id } })
    if (!existing) {
      return NextResponse.json(
        { success: false, error: 'Invoice not found' },
        { status: 404 }
      )
    }

    const { createdAt, updatedAt, user, subscription, payments, commissions, ...updateData } = body as Record<string, unknown>

    // Recalculate total if amounts changed
    if (updateData.amount !== undefined || updateData.tax !== undefined || updateData.discount !== undefined || updateData.lateFee !== undefined) {
      const amount = (updateData.amount ?? existing.amount) as number
      const tax = (updateData.tax ?? existing.tax) as number
      const discount = (updateData.discount ?? existing.discount) as number
      const lateFee = (updateData.lateFee ?? existing.lateFee) as number
      updateData.totalAmount = amount + tax + lateFee - discount
    }

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

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

    if (!action || !['mark_paid', 'mark_unpaid', 'mark_due'].includes(action)) {
      return NextResponse.json(
        { success: false, error: 'Invalid action. Use mark_paid, mark_unpaid, or mark_due' },
        { status: 400 }
      )
    }

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

    const statusMap: Record<string, string> = {
      mark_paid: 'PAID',
      mark_unpaid: 'UNPAID',
      mark_due: 'DUE',
    }

    const updateData: Record<string, unknown> = { status: statusMap[action] }

    if (action === 'mark_paid') {
      updateData.paidAmount = existing.totalAmount
    }

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

    return NextResponse.json({
      success: true,
      data: invoice,
      message: `Invoice marked as ${statusMap[action]}`,
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
