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

export async function DELETE(req: NextRequest) {
    const token = req.cookies.get('token')?.value
    const isAdmin = verifyAdminToken(token)
    if (!isAdmin) {
        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 })

    try {
        await bd.query('DELETE FROM games WHERE id = ?', [id])
        return NextResponse.json({ success: true })
    } catch {
        return NextResponse.json({ error: 'Ошибка при удалении' }, { status: 500 })
    }
}

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 id, title, image_url, platform FROM games')
        return NextResponse.json(rows)
    } catch {
        return NextResponse.json({ error: 'Ошибка БД' }, { status: 500 })
    }
}
