import { NextRequest, NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import { prisma } from '@/lib/prisma';

export async function POST(_request: NextRequest) {
  try {
    const cookieStore = await cookies();
    const sessionCookie = cookieStore.get('sessionToken');

    if (sessionCookie) {
      // Delete the session from the database
      await prisma.session.delete({
        where: {
          token: sessionCookie.value,
        },
      }).catch(() => {
        // Session might not exist, that's ok
      });

      // Clear the cookie
      cookieStore.delete('sessionToken');
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Logout error:', error);
    return NextResponse.json(
      { error: 'An error occurred during logout' },
      { status: 500 }
    );
  }
}
