import type { APIRoute } from 'astro';
import Database from 'better-sqlite3';
import { join } from 'path';
import { mkdirSync, existsSync } from 'fs';

export const prerender = false;

const DATA_DIR = join(process.cwd(), 'data');
const DB_PATH = join(DATA_DIR, 'consent.db');

function getDb() {
  if (!existsSync(DATA_DIR)) {
    mkdirSync(DATA_DIR, { recursive: true });
  }
  const db = new Database(DB_PATH);
  db.exec(`
    CREATE TABLE IF NOT EXISTS ConsentLog (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      sessionId TEXT UNIQUE NOT NULL,
      timestamp TEXT NOT NULL,
      essential INTEGER NOT NULL DEFAULT 0,
      analytics INTEGER NOT NULL DEFAULT 0,
      marketing INTEGER NOT NULL DEFAULT 0,
      policyVersion TEXT NOT NULL,
      ipHash TEXT,
      userAgent TEXT
    )
  `);
  return db;
}

export const DELETE: APIRoute = async ({ params }) => {
  try {
    const sessionId = params.sessionId;
    if (!sessionId) {
      return new Response(
        JSON.stringify({ error: 'Missing sessionId' }),
        { status: 400, headers: { 'Content-Type': 'application/json' } }
      );
    }

    const db = getDb();
    const stmt = db.prepare('DELETE FROM ConsentLog WHERE sessionId = ?');
    stmt.run(sessionId);
    db.close();

    return new Response(
      JSON.stringify({ success: true, message: 'Consent deleted' }),
      { status: 200, headers: { 'Content-Type': 'application/json' } }
    );
  } catch (error) {
    console.error('Error deleting consent:', error);
    return new Response(
      JSON.stringify({ error: 'Failed to delete consent' }),
      { status: 500, headers: { 'Content-Type': 'application/json' } }
    );
  }
};