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

    // Get notes
    const notes = await queryJobPanelDb<RowDataPacket[]>(
      `SELECT n.*, u.username as author_name, u.avatarUrl as author_avatar
       FROM job_panel_notes n
       LEFT JOIN User u ON n.created_by = u.id
       WHERE n.panel_id = ? 
       ORDER BY n.is_pinned DESC, n.created_at DESC`,
      [id]
    )

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

// POST - Create note
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 { title, content, category, isPinned } = body

    if (!title || !content) {
      return NextResponse.json({ error: 'Title and content required' }, { status: 400 })
    }

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

    // Create note
    const noteId = uuidv4()
    await queryJobPanelDb(
      `INSERT INTO job_panel_notes (id, panel_id, title, content, category, is_pinned, created_by)
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [noteId, id, title, content, category || 'general', isPinned ? 1 : 0, session.userId]
    )

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

// PUT - Update note
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
    const body = await request.json()
    const { noteId, title, content, category, isPinned } = body

    if (!noteId) {
      return NextResponse.json({ error: 'Note 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 })
    }

    const updates: string[] = []
    const values: (string | number)[] = []

    if (title) {
      updates.push('title = ?')
      values.push(title)
    }
    if (content) {
      updates.push('content = ?')
      values.push(content)
    }
    if (category) {
      updates.push('category = ?')
      values.push(category)
    }
    if (isPinned !== undefined) {
      updates.push('is_pinned = ?')
      values.push(isPinned ? 1 : 0)
    }

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

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

// DELETE - Delete note
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 noteId = searchParams.get('noteId')

    if (!noteId) {
      return NextResponse.json({ error: 'Note 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_notes WHERE id = ? AND panel_id = ?', [noteId, id])

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