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

// GET - List dispatch logs
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 featureEnabled = await isFeatureEnabled(id, 'dispatch_logs')
    if (!featureEnabled && !access.isSuperadmin) {
      return NextResponse.json({ logs: [], featureDisabled: true })
    }

    // Get logs
    const logs = await queryJobPanelDb<RowDataPacket[]>(
      `SELECT * FROM job_panel_dispatch_logs 
       WHERE panel_id = ? 
       ORDER BY created_at DESC 
       LIMIT 100`,
      [id]
    )

    return NextResponse.json({ logs })
  } catch (error) {
    console.error('[Dispatch] Error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

// POST - Create dispatch log
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
    const body = await request.json()
    const { type, priority, title, description, location } = body

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

    // Create log entry
    const logId = uuidv4()
    await queryJobPanelDb(
      `INSERT INTO job_panel_dispatch_logs (id, panel_id, type, priority, title, description, location, created_by)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
      [logId, id, type || 'other', priority || 'medium', title, description || null, location || null, session.userId]
    )

    return NextResponse.json({ success: true, logId })
  } catch (error) {
    console.error('[Dispatch] Error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}

// DELETE - Delete dispatch log
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
    const { searchParams } = new URL(request.url)
    const logId = searchParams.get('logId')

    if (!logId) {
      return NextResponse.json({ error: 'Log ID required' }, { status: 400 })
    }

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

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

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error('[Dispatch] Error:', error)
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
  }
}
