/* @vitest-environment node */

import { describe, it, expect, vi, beforeEach } from "vitest";

vi.mock("@/lib/auth/session", () => ({
	getSession: vi.fn(),
}));

import { getSession } from "@/lib/auth/session";
import { GET, dynamic } from "./route.js";

describe("GET /api/auth/me", () => {
	beforeEach(() => {
		vi.clearAllMocks();
	});

	it('exports dynamic="force-dynamic" (RHL-006)', () => {
		expect(dynamic).toBe("force-dynamic");
	});

	it("returns { user: null } when unauthenticated", async () => {
		getSession.mockResolvedValue(null);

		const res = await GET();
		expect(res.status).toBe(200);
		expect(await res.json()).toEqual({ user: null });
	});

	it("returns user payload when authenticated (includes email)", async () => {
		getSession.mockResolvedValue({
			userId: "u1",
			role: "branch",
			branchId: "NL01",
			email: "nl01@example.com",
			mustChangePassword: true,
		});

		const res = await GET();
		expect(res.status).toBe(200);
		expect(await res.json()).toEqual({
			user: {
				userId: "u1",
				role: "branch",
				branchId: "NL01",
				email: "nl01@example.com",
				mustChangePassword: true,
			},
		});
	});

	it("returns email=null and mustChangePassword=false when missing", async () => {
		getSession.mockResolvedValue({
			userId: "u2",
			role: "admin",
			branchId: null,
			email: null,
			mustChangePassword: undefined,
		});

		const res = await GET();
		expect(res.status).toBe(200);
		expect(await res.json()).toEqual({
			user: {
				userId: "u2",
				role: "admin",
				branchId: null,
				email: null,
				mustChangePassword: false,
			},
		});
	});
});
