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
    const isAdmin = verifyAdminToken(token)

    if (!isAdmin) {
        return NextResponse.json({ error: 'Доступ запрещён' }, { status: 401 })
    }

    try {
        const [rows] = await bd.query(
            'SELECT game_type, room_type, day_type, hour_1, hour_3, hour_5, night FROM prices'
        )
        return NextResponse.json(rows)
    } catch {
        return NextResponse.json({ error: 'Ошибка БД' }, { status: 500 })
    }
}

export async function PUT(req: NextRequest) {
    const token = req.cookies.get('token')?.value
    const isAdmin = verifyAdminToken(token)

    if (!isAdmin) {
        return NextResponse.json({ error: 'Доступ запрещён' }, { status: 401 })
    }

    const data = await req.json()
    const {
        game_type,
        room_type,
        day_type,
        hour_1,
        hour_3,
        hour_5,
        night,
    } = data

    if (!game_type || !room_type || !day_type) {
        return NextResponse.json({ error: 'Ключевые поля отсутствуют' }, { status: 400 })
    }

    try {
        await bd.query(
            `UPDATE prices
       SET hour_1 = ?, hour_3 = ?, hour_5 = ?, night = ?
       WHERE game_type = ? AND room_type = ? AND day_type = ?`,
            [hour_1, hour_3, hour_5, night, game_type, room_type, day_type]
        )

        return NextResponse.json({ success: true })
    } catch (error) {
        console.error(error)
        return NextResponse.json({ error: 'Ошибка при обновлении' }, { status: 500 })
    }
}
