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 GET: APIRoute = async ({ request, url }) => {
  try {
    const searchParams = new URL(url).searchParams;
    const sessionId = searchParams.get('sessionId');
    const limit = parseInt(searchParams.get('limit') || '100');

    // If sessionId provided, get specific consent
    if (sessionId) {
      const consent = await db.select()
        .from(ConsentLog)
        .where(eq(ConsentLog.sessionId, sessionId))
        .limit(1);

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

      return new Response(JSON.stringify({ success: true, data: consent[0] }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    // Get all consent records (for admin)
    const consents = await db.select()
      .from(ConsentLog)
      .orderBy((t) => t.timestamp)
      .limit(limit);

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