import { NextRequest, NextResponse } from 'next/server'
import { getSession } from '@/lib/auth'
import { queryJobPanelDb } from '@/lib/job-panel-db'
import { checkPanelAccess, isFeatureEnabled, hasPermission } from '@/lib/services/job-panel-permissions'
import { sendFactionWebhook, EMBED_COLORS } from '@/lib/services/job-panel-webhooks'
import { v4 as uuidv4 } from 'uuid'
import type { RowDataPacket } from 'mysql2'

// GET - List invoices
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getSession()
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { id } = await params

    // Check access
    const access = await checkPanelAccess(id)
    if (!access?.canAccess) {
      return NextResponse.json({ error: 'Access denied' }, { status: 403 })
    }

    // Check if feature is enabled (superadmins can always access)
    const enabled = await isFeatureEnabled(id, 'billing_invoices')
    if (!enabled && !access.isSuperadmin) {
      return NextResponse.json({ invoices: [], featureDisabled: true })
    }

    const invoices = await queryJobPanelDb<RowDataPacket[]>(
      'SELECT * FROM job_panel_invoices WHERE panel_id = ? ORDER BY created_at DESC',
      [id]
    )

    return NextResponse.json({
      invoices: invoices.map(inv => ({
        id: inv.id,
        invoiceNumber: inv.invoice_number,
        citizenId: inv.citizen_id,
        citizenName: inv.citizen_name,
        amount: parseFloat(inv.amount),
        reason: inv.reason,
        status: inv.status,
        dueDate: inv.due_date,
        paidAt: inv.paid_at,
        createdBy: inv.created_by,
        createdByName: inv.created_by_name,
        createdAt: inv.created_at,
      })),
    })
  } catch (error) {
    console.error('[Invoices] GET error:', error)
    return NextResponse.json({ error: 'Failed to fetch invoices' }, { status: 500 })
  }
}

// POST - Create invoice
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getSession()
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { id } = await params

    // Check access
    const access = await checkPanelAccess(id)
    if (!access?.canAccess) {
      return NextResponse.json({ error: 'Access denied' }, { status: 403 })
    }

    if (!hasPermission(access, 'send_invoices')) {
      return NextResponse.json({ error: 'Permission denied' }, { status: 403 })
    }

    const body = await request.json()
    const { citizenId, citizenName, amount, reason, dueDate } = body

    if (!citizenId || !amount) {
      return NextResponse.json({ error: 'Citizen ID and amount are required' }, { status: 400 })
    }

    const invoiceId = uuidv4()
    const invoiceNumber = `INV-${Date.now().toString(36).toUpperCase()}`

    await queryJobPanelDb(
      `INSERT INTO job_panel_invoices 
       (id, panel_id, invoice_number, citizen_id, citizen_name, amount, reason, due_date, created_by, created_by_name)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        invoiceId,
        id,
        invoiceNumber,
        citizenId,
        citizenName || null,
        amount,
        reason || null,
        dueDate || null,
        session.discordId,
        session.username || 'Unknown',
      ]
    )

    // Send webhook
    await sendFactionWebhook(
      id,
      'Invoice Created',
      `A new invoice has been created`,
      [
        { name: 'Invoice #', value: invoiceNumber, inline: true },
        { name: 'Amount', value: `$${amount.toLocaleString()}`, inline: true },
        { name: 'Citizen', value: citizenName || citizenId, inline: true },
        { name: 'Reason', value: reason || 'No reason provided', inline: false },
      ],
      EMBED_COLORS.INFO,
      session.discordId
    )

    return NextResponse.json({ success: true, invoiceId, invoiceNumber })
  } catch (error) {
    console.error('[Invoices] POST error:', error)
    return NextResponse.json({ error: 'Failed to create invoice' }, { status: 500 })
  }
}

// PUT - Update invoice
export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getSession()
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { id } = await params

    // Check access
    const access = await checkPanelAccess(id)
    if (!access?.canAccess) {
      return NextResponse.json({ error: 'Access denied' }, { status: 403 })
    }

    if (!hasPermission(access, 'send_invoices')) {
      return NextResponse.json({ error: 'Permission denied' }, { status: 403 })
    }

    const body = await request.json()
    const { invoiceId, status } = body

    if (!invoiceId) {
      return NextResponse.json({ error: 'Invoice ID is required' }, { status: 400 })
    }

    const updates: string[] = []
    const values: unknown[] = []

    if (status) {
      updates.push('status = ?')
      values.push(status)
      
      if (status === 'PAID') {
        updates.push('paid_at = CURRENT_TIMESTAMP')
      }
    }

    if (updates.length > 0) {
      values.push(invoiceId, id)
      await queryJobPanelDb(
        `UPDATE job_panel_invoices SET ${updates.join(', ')} WHERE id = ? AND panel_id = ?`,
        values
      )
    }

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('[Invoices] PUT error:', error)
    return NextResponse.json({ error: 'Failed to update invoice' }, { status: 500 })
  }
}

// DELETE - Remove invoice
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await getSession()
    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const { id } = await params

    // Check access
    const access = await checkPanelAccess(id)
    if (!access?.canAccess) {
      return NextResponse.json({ error: 'Access denied' }, { status: 403 })
    }

    if (!hasPermission(access, 'send_invoices')) {
      return NextResponse.json({ error: 'Permission denied' }, { status: 403 })
    }

    const { searchParams } = new URL(request.url)
    const invoiceId = searchParams.get('invoiceId')

    if (!invoiceId) {
      return NextResponse.json({ error: 'Invoice ID is required' }, { status: 400 })
    }

    await queryJobPanelDb(
      'DELETE FROM job_panel_invoices WHERE id = ? AND panel_id = ?',
      [invoiceId, id]
    )

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('[Invoices] DELETE error:', error)
    return NextResponse.json({ error: 'Failed to delete invoice' }, { status: 500 })
  }
}
