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 { logRecordChange } from '@/lib/services/job-panel-webhooks'
import { v4 as uuidv4 } from 'uuid'
import type { RowDataPacket } from 'mysql2'

// GET - List criminal records
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, 'criminal_records')
    if (!enabled && !access.isSuperadmin) {
      return NextResponse.json({ records: [], featureDisabled: true })
    }

    // Check permission (superadmins have all permissions)
    if (!access.isSuperadmin && !hasPermission(access, 'view_data')) {
      return NextResponse.json({ error: 'Permission denied' }, { status: 403 })
    }

    const { searchParams } = new URL(request.url)
    const citizenId = searchParams.get('citizenId')
    const status = searchParams.get('status')
    const limit = parseInt(searchParams.get('limit') || '50')
    const offset = parseInt(searchParams.get('offset') || '0')

    let query = 'SELECT * FROM job_panel_criminal_records WHERE panel_id = ?'
    const queryParams: unknown[] = [id]

    if (citizenId) {
      query += ' AND citizen_id = ?'
      queryParams.push(citizenId)
    }

    if (status) {
      query += ' AND status = ?'
      queryParams.push(status)
    }

    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?'
    queryParams.push(limit, offset)

    const records = await queryJobPanelDb<RowDataPacket[]>(query, queryParams)

    // Get total count
    let countQuery = 'SELECT COUNT(*) as count FROM job_panel_criminal_records WHERE panel_id = ?'
    const countParams: unknown[] = [id]
    if (citizenId) {
      countQuery += ' AND citizen_id = ?'
      countParams.push(citizenId)
    }
    if (status) {
      countQuery += ' AND status = ?'
      countParams.push(status)
    }
    const countResult = await queryJobPanelDb<RowDataPacket[]>(countQuery, countParams)
    const total = countResult[0]?.count || 0

    return NextResponse.json({
      records: records.map(r => ({
        id: r.id,
        citizenId: r.citizen_id,
        citizenName: r.citizen_name,
        title: r.title,
        description: r.description,
        offenseType: r.offense_type,
        fineAmount: parseFloat(r.fine_amount || 0),
        jailTime: r.jail_time,
        status: r.status,
        createdBy: r.created_by,
        createdByName: r.created_by_name,
        createdAt: r.created_at,
        updatedAt: r.updated_at,
      })),
      total,
      limit,
      offset,
    })
  } catch (error) {
    console.error('[Records] GET error:', error)
    return NextResponse.json({ error: 'Failed to fetch records' }, { status: 500 })
  }
}

// POST - Create criminal record
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 })
    }

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

    const body = await request.json()
    const { citizenId, citizenName, title, description, offenseType, fineAmount, jailTime } = body

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

    const recordId = uuidv4()

    await queryJobPanelDb(
      `INSERT INTO job_panel_criminal_records 
       (id, panel_id, citizen_id, citizen_name, title, description, offense_type, fine_amount, jail_time, created_by, created_by_name)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
      [
        recordId,
        id,
        citizenId,
        citizenName || null,
        title,
        description || null,
        offenseType || 'INFRACTION',
        fineAmount || 0,
        jailTime || 0,
        session.userId,
        session.discordId,
      ]
    )

    // Log and send webhook
    await logRecordChange(
      id,
      'CREATED',
      session.userId,
      session.discordId,
      recordId,
      title,
      citizenName || citizenId,
      { offenseType, fineAmount, jailTime }
    )

    return NextResponse.json({ success: true, recordId })
  } catch (error) {
    console.error('[Records] POST error:', error)
    return NextResponse.json({ error: 'Failed to create record' }, { status: 500 })
  }
}

// PUT - Update criminal record
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 })
    }

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

    const body = await request.json()
    const { recordId, title, description, offenseType, fineAmount, jailTime, status } = body

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

    // Get existing record
    const existing = await queryJobPanelDb<RowDataPacket[]>(
      'SELECT * FROM job_panel_criminal_records WHERE id = ? AND panel_id = ?',
      [recordId, id]
    )

    if (existing.length === 0) {
      return NextResponse.json({ error: 'Record not found' }, { status: 404 })
    }

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

    if (title !== undefined) {
      updates.push('title = ?')
      values.push(title)
    }
    if (description !== undefined) {
      updates.push('description = ?')
      values.push(description)
    }
    if (offenseType !== undefined) {
      updates.push('offense_type = ?')
      values.push(offenseType)
    }
    if (fineAmount !== undefined) {
      updates.push('fine_amount = ?')
      values.push(fineAmount)
    }
    if (jailTime !== undefined) {
      updates.push('jail_time = ?')
      values.push(jailTime)
    }
    if (status !== undefined) {
      updates.push('status = ?')
      values.push(status)
    }

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

      // Log and send webhook
      await logRecordChange(
        id,
        'EDITED',
        session.userId,
        session.discordId,
        recordId,
        title || existing[0].title,
        existing[0].citizen_name || existing[0].citizen_id
      )
    }

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

// DELETE - Delete criminal record
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 })
    }

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

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

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

    // Get existing record for logging
    const existing = await queryJobPanelDb<RowDataPacket[]>(
      'SELECT * FROM job_panel_criminal_records WHERE id = ? AND panel_id = ?',
      [recordId, id]
    )

    if (existing.length === 0) {
      return NextResponse.json({ error: 'Record not found' }, { status: 404 })
    }

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

    // Log and send webhook
    await logRecordChange(
      id,
      'DELETED',
      session.userId,
      session.discordId,
      recordId,
      existing[0].title,
      existing[0].citizen_name || existing[0].citizen_id
    )

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