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

const { mockCheckPermissions, mockRedirect } = vi.hoisted(() => ({
  mockCheckPermissions: vi.fn(),
  mockRedirect: vi.fn((status: number, location: string) => {
    throw { status, location };
  }),
}));

vi.mock("$lib/permissions", () => ({
  checkPermissions: mockCheckPermissions,
}));
vi.mock("@sveltejs/kit", () => ({
  redirect: mockRedirect,
}));

import { load } from "./+page.server";

describe("admin/reports +page.server.ts load", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it("redirects to /login when no access token", async () => {
    await expect(
      load({
        locals: {},
        parent: vi.fn().mockResolvedValue({}),
      } as any),
    ).rejects.toEqual(
      expect.objectContaining({ status: 303, location: "/login" }),
    );
  });

  it("redirects to /admin when reports permission is false", async () => {
    await expect(
      load({
        locals: { session: { accessToken: "tok" } },
        parent: vi.fn().mockResolvedValue({
          permissions: { "ui.navigation.reports.view": false },
        }),
      } as any),
    ).rejects.toEqual(
      expect.objectContaining({ status: 303, location: "/admin" }),
    );
  });

  it("returns accessToken when permitted", async () => {
    const result = await load({
      locals: { session: { accessToken: "tok" } },
      parent: vi.fn().mockResolvedValue({
        permissions: { "ui.navigation.reports.view": true },
      }),
    } as any);

    expect(result).toEqual({ accessToken: "tok" });
  });
});
