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 vehicles
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, 'vehicle_management')
    if (!enabled && !access.isSuperadmin) {
      return NextResponse.json({ vehicles: [], featureDisabled: true })
    }

    const vehicles = await queryJobPanelDb<RowDataPacket[]>(
      'SELECT * FROM job_panel_vehicles WHERE panel_id = ? ORDER BY status, plate',
      [id]
    )

    return NextResponse.json({
      vehicles: vehicles.map(v => ({
        id: v.id,
        plate: v.plate,
        model: v.model,
        label: v.label,
        assignedTo: v.assigned_to,
        assignedToName: v.assigned_to_name,
        status: v.status,
        notes: v.notes,
        createdAt: v.created_at,
        updatedAt: v.updated_at,
      })),
    })
  } catch (error) {
    console.error('[Vehicles] GET error:', error)
    return NextResponse.json({ error: 'Failed to fetch vehicles' }, { status: 500 })
  }
}

// POST - Add vehicle
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 (!access.isSuperadmin && !hasPermission(access, 'manage_vehicles')) {
      return NextResponse.json({ error: 'Permission denied' }, { status: 403 })
    }

    const body = await request.json()
    const { plate, model, label, notes } = body

    if (!plate) {
      return NextResponse.json({ error: 'Plate is required' }, { status: 400 })
    }

    const vehicleId = uuidv4()

    await queryJobPanelDb(
      `INSERT INTO job_panel_vehicles (id, panel_id, plate, model, label, notes)
       VALUES (?, ?, ?, ?, ?, ?)`,
      [vehicleId, id, plate.toUpperCase(), model || null, label || null, notes || null]
    )

    // Send webhook
    await sendFactionWebhook(
      id,
      'Vehicle Added',
      `A new vehicle has been added to the fleet`,
      [
        { name: 'Plate', value: plate.toUpperCase(), inline: true },
        { name: 'Model', value: model || 'N/A', inline: true },
      ],
      EMBED_COLORS.SUCCESS,
      session.discordId
    )

    return NextResponse.json({ success: true, vehicleId })
  } catch (error) {
    console.error('[Vehicles] POST error:', error)
    return NextResponse.json({ error: 'Failed to add vehicle' }, { status: 500 })
  }
}

// PUT - Update vehicle
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 (!access.isSuperadmin && !hasPermission(access, 'manage_vehicles')) {
      return NextResponse.json({ error: 'Permission denied' }, { status: 403 })
    }

    const body = await request.json()
    const { vehicleId, assignedTo, assignedToName, status, notes } = body

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

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

    if (assignedTo !== undefined) {
      updates.push('assigned_to = ?')
      values.push(assignedTo || null)
    }
    if (assignedToName !== undefined) {
      updates.push('assigned_to_name = ?')
      values.push(assignedToName || null)
    }
    if (status !== undefined) {
      updates.push('status = ?')
      values.push(status)
    }
    if (notes !== undefined) {
      updates.push('notes = ?')
      values.push(notes)
    }

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

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

// DELETE - Remove vehicle
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 (!access.isSuperadmin && !hasPermission(access, 'manage_vehicles')) {
      return NextResponse.json({ error: 'Permission denied' }, { status: 403 })
    }

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

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

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

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