import { NextRequest, NextResponse } from 'next/server'
import { bd } from '@/lib/bd'
import { verifyAdminToken } from '@/lib/verifyAdmin'
import type { ResultSetHeader, FieldPacket } from 'mysql2'

// GET — получить все записи
export async function GET(req: NextRequest) {
    const token = req.cookies.get('token')?.value
    if (!verifyAdminToken(token)) return NextResponse.json({ error: 'Нет доступа' }, { status: 401 })

    const [rows] = await bd.query('SELECT * FROM faq ORDER BY id DESC')
    return NextResponse.json(rows)
}

// POST — создать новую запись
export async function POST(req: NextRequest) {
    const token = req.cookies.get('token')?.value
    if (!verifyAdminToken(token)) return NextResponse.json({ error: 'Нет доступа' }, { status: 401 })

    const { title, description } = await req.json()
    if (!title || !description) {
        return NextResponse.json({ error: 'Заполните все поля' }, { status: 400 })
    }

    const [result]: [ResultSetHeader, FieldPacket[]] = await bd.query(
        'INSERT INTO faq (title, description) VALUES (?, ?)',
        [title, description]
    )

    return NextResponse.json({ id: result.insertId, title, description })
}

// PUT — редактировать существующую
export async function PUT(req: NextRequest) {
    const token = req.cookies.get('token')?.value
    if (!verifyAdminToken(token)) return NextResponse.json({ error: 'Нет доступа' }, { status: 401 })

    const { id, title, description } = await req.json()
    if (!id || !title || !description) {
        return NextResponse.json({ error: 'Заполните все поля' }, { status: 400 })
    }

    await bd.query('UPDATE faq SET title = ?, description = ? WHERE id = ?', [
        title, description, id
    ])

    return NextResponse.json({ success: true })
}

// DELETE — удалить запись
export async function DELETE(req: NextRequest) {
    const token = req.cookies.get('token')?.value
    if (!verifyAdminToken(token)) return NextResponse.json({ error: 'Нет доступа' }, { status: 401 })

    const { searchParams } = new URL(req.url)
    const id = searchParams.get('id')
    if (!id) return NextResponse.json({ error: 'ID не указан' }, { status: 400 })

    await bd.query('DELETE FROM faq WHERE id = ?', [id])
    return NextResponse.json({ success: true })
}
