// tdd-guard:skip — Next.js route handler is integration-level glue; the
// payload-shape logic lives in lib/gdpr/export.ts with its own tests.
import { NextResponse } from "next/server"

import { createClient } from "@/lib/supabase/server"
import { buildGdprExport } from "@/lib/gdpr/export"
import { logger } from "@/lib/logger"

/**
 * GDPR Article 15 — Auskunft (KAR-529).
 *
 * Returns the full set of personal data the system holds about the
 * authenticated user as a downloadable JSON file. RLS does the row-level
 * filtering; this endpoint only authenticates that the caller has a session
 * before assembling the export.
 *
 * Auth: required (Supabase session via cookie).
 * Method: GET.
 * Response: JSON download with the user's data, schema_version: 1.
 */
export async function GET() {
  const supabase = await createClient()
  const { data: claimsData } = await supabase.auth.getClaims()
  if (!claimsData?.claims) {
    return NextResponse.json({ error: "unauthorized" }, { status: 401 })
  }

  const userId = claimsData.claims.sub
  const payload = await buildGdprExport(supabase, userId)

  logger.info("gdpr.export.served", {
    user_id: userId,
    table_count: Object.keys(payload.tables).length,
    schema_version: payload.schema_version,
  })

  return new NextResponse(JSON.stringify(payload, null, 2), {
    status: 200,
    headers: {
      "Content-Type": "application/json; charset=utf-8",
      "Content-Disposition": `attachment; filename="user-data-${userId}.json"`,
      // Defensive — this is sensitive personal data, never cache.
      "Cache-Control": "no-store, max-age=0",
    },
  })
}
