import { createServerFn } from "@tanstack/react-start";
import { requireSupabaseAuth } from "@/integrations/supabase/auth-middleware";

const USER_TABLES = [
  "profiles",
  "transactions",
  "budgets",
  "goals",
  "decisions",
  "simulations",
  "ai_chats",
  "ai_conversations",
  "ai_insights",
  "subscriptions",
] as const;

/** Returns every row this user owns, as a portable JSON archive. */
export const exportUserData = createServerFn({ method: "GET" })
  .middleware([requireSupabaseAuth])
  .handler(async ({ context }) => {
    const supabase = context.supabase as any;
    const { userId, claims } = context;

    const entries = await Promise.all(
      USER_TABLES.map(async (table) => {
        const col = table === "profiles" ? "id" : "user_id";
        const { data } = await supabase.from(table).select("*").eq(col, userId);
        return [table, (data ?? []) as any[]] as const;
      }),
    );

    const { data: files } = await supabase.storage.from("receipts").list(userId, { limit: 1000 });

    return {
      exportedAt: new Date().toISOString(),
      format: "prudentia-export-v1",
      account: { id: userId, email: (claims as any)?.email ?? null },
      receipts: (files ?? []).map((f: any) => ({ name: f.name, size: (f as any)?.metadata?.size ?? null, createdAt: f.created_at })),
      data: Object.fromEntries(entries) as Record<string, any[]>,
    };
  });

/** Permanently deletes all user data, uploaded receipts, and the login itself. */
export const deleteAccount = createServerFn({ method: "POST" })
  .middleware([requireSupabaseAuth])
  .handler(async ({ context }) => {
    const supabase = context.supabase as any;
    const { userId } = context;

    // 1. Uploaded receipts.
    const { data: files } = await supabase.storage.from("receipts").list(userId, { limit: 1000 });
    if (files?.length) {
      await supabase.storage.from("receipts").remove(files.map((f: any) => `${userId}/${f.name}`));
    }

    // 2. Application data (RLS-scoped to this user).
    for (const table of USER_TABLES) {
      if (table === "subscriptions") continue; // service-managed; removed with the login below
      const col = table === "profiles" ? "id" : "user_id";
      await supabase.from(table).delete().eq(col, userId);
    }

    // 3. Billing record + the login itself.
    const { supabaseAdmin } = await import("@/integrations/supabase/client.server");
    await (supabaseAdmin as any).from("subscriptions").delete().eq("user_id", userId);
    const { error } = await supabaseAdmin.auth.admin.deleteUser(userId);
    if (error) throw new Error(error.message);

    return { ok: true };
  });
