import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";

function source(relativePath: string): string {
  return fs.readFileSync(path.join(process.cwd(), relativePath), "utf8");
}

describe("donor account soft deletion", () => {
  const migration = source(
    "supabase/migrations/202607270003_donor_transfer_total_and_account_deletion.sql"
  ).toLowerCase();
  const actions = source("src/app/actions/admin.ts");
  const donorPage = source("src/app/admin/donors/[id]/page.tsx");
  const donorList = source("src/app/admin/donors/page.tsx");

  it("adds a tombstone without changing historical foreign keys", () => {
    expect(migration).toContain("add column if not exists deleted_at timestamptz");
    expect(migration).not.toContain("drop constraint");
    expect(migration).not.toContain("on delete cascade");
    expect(migration).not.toContain("delete from");
  });

  it("blocks Auth access and tombstones only the profile", () => {
    const start = actions.indexOf("export async function deleteSponsorAccountAction");
    const end = actions.indexOf("export async function resetAccountPasswordAction", start);
    const deletionAction = actions.slice(start, end);

    expect(start).toBeGreaterThan(-1);
    expect(deletionAction).toContain('ban_duration: "876000h"');
    expect(deletionAction).toContain("is_active: false");
    expect(deletionAction).toContain("deleted_at:");
    expect(deletionAction).toContain('action: "sponsor.account_deleted"');
    expect(deletionAction).not.toContain("deleteUser");
    expect(deletionAction).not.toContain(".delete()");
  });

  it("offers the guarded action and hides tombstoned accounts from the main list", () => {
    expect(donorPage).toContain("deleteSponsorAccountAction");
    expect(donorPage).toContain("لن تحذف التحويلات أو الإيصالات أو الدفعات أو المستندات");
    expect(donorList).toContain('.is("deleted_at", null)');
  });
});
