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 value, type FROM contacts'
        )
        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 { value, type } = data;

    if (!value || !type) {
        return NextResponse.json({ error: 'value и type обязательны' }, { status: 400 });
    }

    try {
        await bd.query(
            `UPDATE contacts SET value = ? WHERE type = ?`,
            [value, type]
        );

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