// @vitest-environment node

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

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

describe("unified role-aware login", () => {
  it("uses one identifier action and redirects by profile role", async () => {
    const auth = await source("src/app/actions/auth.ts");

    expect(auth).toContain('identifier: formData.get("identifier")');
    expect(auth).toContain('parsed.data.identifier.type === "email"');
    expect(auth).toContain('profile.role === "admin"');
    expect(auth).toContain('"/donor/security?required=1"');
    expect(auth).toContain('        : "/donor"');
    expect(auth).not.toContain("adminLoginAction");
  });

  it("renders only the shared form and redirects the legacy admin route", async () => {
    const form = await source("src/components/forms/login-form.tsx");
    const legacyRoute = await source("src/app/(public)/admin-login/page.tsx");
    const profileGuard = await source("src/lib/auth.ts");

    expect(form).toContain('name="identifier"');
    expect(form).toContain("البريد الإلكتروني أو رقم الهاتف");
    expect(form).not.toContain('name="phone"');
    expect(legacyRoute).toContain('redirect("/login")');
    expect(profileGuard).not.toContain("/admin-login");
  });
});
