import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';
import {
  ADMIN_SESSION_COOKIE_NAME,
  getAdminSessionSecret,
  unsignSessionId,
} from '@/lib/admin-session-cookie';

export async function POST(req: NextRequest) {
  const signedValue = req.cookies.get(ADMIN_SESSION_COOKIE_NAME)?.value;
  if (signedValue) {
    const sessionId = unsignSessionId(signedValue, getAdminSessionSecret());
    if (sessionId) {
      const db = getDb();
      db.prepare('DELETE FROM admin_sessions WHERE id = ?').run(sessionId);
    }
  }
  const res = NextResponse.json({ success: true });
  res.cookies.set(ADMIN_SESSION_COOKIE_NAME, '', { path: '/', expires: new Date(0) });
  return res;
}
