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 POST: APIRoute = async ({ request }) => {
  try {
    const body = await request.json();
    const { sessionId, essential, analytics, marketing, policyVersion, locale } = body;

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

    const ip = request.headers.get('x-forwarded-for') || request.headers.get('x-real-ip') || '';
    const ipHash = ip ? await hashIP(ip) : '';
    const userAgent = request.headers.get('user-agent') || '';

    const existing = await db.select().from(ConsentLog).where(eq(ConsentLog.sessionId, sessionId)).limit(1);

    if (existing.length > 0) {
      await db.update(ConsentLog)
        .set({
          essential,
          analytics,
          marketing,
          policyVersion,
          locale,
          ipHash,
          userAgent,
          timestamp: new Date().toISOString()
        })
        .where(eq(ConsentLog.sessionId, sessionId));

      return new Response(JSON.stringify({ success: true, action: 'updated' }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' }
      });
    }

    await db.insert(ConsentLog).values({
      sessionId,
      timestamp: new Date().toISOString(),
      locale: locale || 'th',
      essential: essential !== false,
      analytics: analytics || false,
      marketing: marketing || false,
      policyVersion: policyVersion || '1.0',
      ipHash,
      userAgent
    });

    return new Response(JSON.stringify({ success: true, action: 'created' }), {
      status: 201,
      headers: { 'Content-Type': 'application/json' }
    });
  } catch (error) {
    console.error('Consent API error:', error);
    return new Response(JSON.stringify({ error: 'Internal server error' }), {
      status: 500,
      headers: { 'Content-Type': 'application/json' }
    });
  }
};

async function hashIP(ip: string): Promise<string> {
  const encoder = new TextEncoder();
  const data = encoder.encode(ip);
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
  return hashHex.substring(0, 16);
}
