/**
 * GDPR Article 17 right-to-be-forgotten orchestration (KAR-529).
 *
 * Hard-deleting rows that participate in FK chains and audit trails breaks
 * referential integrity and (worse) makes the deletion event itself
 * untraceable for compliance review. Instead, the deletion request is a
 * three-step process:
 *
 *   1. Mark the user profile `account_status = 'deletion_requested'` and
 *      set `deletion_requested_at = now()`. The session-context middleware
 *      then forces a logout on the next request.
 *   2. Emit a structured audit event `gdpr.deletion.requested`. The event
 *      is the legal record of when the user invoked Article 17.
 *   3. Schedule the actual scrub via a separate, operator-supervised job
 *      (out of scope for this file — it lives in supabase scheduled tasks
 *      and is reviewed during the security release). The scrub runs after
 *      the legal retention period for the relevant data class.
 *
 * Why split: the immediate user-visible behaviour (logout, no more access)
 * must be synchronous and irreversible. The scrub may take days to weeks
 * depending on retention rules per data class, and it depends on operator
 * confirmation. Splitting keeps the user-facing endpoint fast and the
 * scrub auditable.
 */
import type { SupabaseClient } from "@supabase/supabase-js"

export type DeletionResult =
  | { ok: true; deletion_requested_at: string }
  | { ok: false; error: string }

/**
 * Request deletion for `userId`.
 *
 * Marks the profile, records the request timestamp, and returns the result.
 * Does **not** delete rows. The downstream scrub job is operator-supervised.
 *
 * RLS guards the UPDATE — only the user themselves (or an admin acting on
 * their behalf via a separate route) can mark their own profile.
 */
export async function requestDeletion(
  client: SupabaseClient,
  userId: string,
  now: () => string = () => new Date().toISOString(),
): Promise<DeletionResult> {
  const requestedAt = now()
  const result = await client
    .from("user_profiles")
    .update({
      account_status: "deletion_requested",
      deletion_requested_at: requestedAt,
    })
    .eq("auth_user_id", userId)
    .select("auth_user_id")
    .maybeSingle()

  if (result.error) {
    return { ok: false, error: result.error.message }
  }
  if (!result.data) {
    return { ok: false, error: "profile_not_found" }
  }

  return { ok: true, deletion_requested_at: requestedAt }
}
