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

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 rooms')
    return NextResponse.json(rows)
}

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

    const data = await req.json()
    const fields = ['name', 'description', 'cpu', 'ram', 'gpu', 'mouse', 'keyboard', 'headphones', 'monitor', 'bracket', 'chair']
    const values = fields.map(f => data[f])

    await bd.query(
        `INSERT INTO rooms (${fields.join(', ')}) VALUES (${fields.map(() => '?').join(', ')})`,
        values
    )

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

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

    const data = await req.json()
    const fields = ['name', 'description', 'cpu', 'ram', 'gpu', 'mouse', 'keyboard', 'headphones', 'monitor', 'bracket', 'chair']
    const values = fields.map(f => data[f])
    values.push(data.id)

    await bd.query(
        `UPDATE rooms SET ${fields.map(f => `${f} = ?`).join(', ')} WHERE id = ?`,
        values
    )

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

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 rooms WHERE id = ?', [id])
    return NextResponse.json({ success: true })
}
