import type { APIRoute } from 'astro';
import { getDb } from '../../../../../db/config';
import schema from '../../../../../db/schema';
import { eq } from 'drizzle-orm';

export const prerender = false;

const db = getDb();
const { ConsentLog } = schema.tables;

export const DELETE: APIRoute = async ({ params, request }) => {
  try {
    // Get sessionId from URL path or query parameter
    const url = new URL(request.url);
    const sessionId = params.sessionId || url.searchParams.get('sessionId');

    if (!sessionId) {
      return new Response(JSON.stringify({ error: 'Session ID is required' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Check if consent exists
    const existing = await db.select()
      .from(ConsentLog)
      .where(eq(ConsentLog.sessionId, sessionId))
      .limit(1);

    if (existing.length === 0) {
      return new Response(JSON.stringify({ error: 'Consent not found' }), {
        status: 404,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Delete consent record (Right to be Forgotten - PDPA)
    await db.delete(ConsentLog).where(eq(ConsentLog.sessionId, sessionId));

    return new Response(JSON.stringify({ success: true, message: 'Consent deleted successfully' }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('Consent DELETE error:', error);
    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};
