import { PermissionKey, SystemRole } from "@capakraken/shared";
import { beforeEach, describe, expect, it, vi } from "vitest";

const { createAuditEntry } = vi.hoisted(() => ({
  createAuditEntry: vi.fn(),
}));

vi.mock("../lib/audit.js", () => ({
  createAuditEntry,
}));

import { orgUnitRouter } from "../router/org-unit.js";
import { createCallerFactory } from "../trpc.js";

const createCaller = createCallerFactory(orgUnitRouter);

function createProtectedCaller(
  db: Record<string, unknown>,
  options: {
    role?: SystemRole;
    granted?: PermissionKey[];
  } = {},
) {
  const { role = SystemRole.USER, granted = [] } = options;

  return createCaller({
    session: {
      user: { email: "user@example.com", name: "User", image: null },
      expires: "2099-01-01T00:00:00.000Z",
    },
    db: db as never,
    dbUser: {
      id: role === SystemRole.ADMIN ? "user_admin" : "user_1",
      systemRole: role,
      permissionOverrides: granted.length > 0 ? { granted } : null,
    },
  });
}

describe("org-unit router", () => {
  beforeEach(() => {
    createAuditEntry.mockReset();
  });

  it("lists org units through the resource-overview router", async () => {
    const findMany = vi.fn().mockResolvedValue([
      { id: "ou_1", name: "Delivery", level: 5, sortOrder: 10, isActive: true },
    ]);

    const caller = createProtectedCaller({
      orgUnit: { findMany },
    }, {
      granted: [PermissionKey.VIEW_ALL_RESOURCES],
    });
    const result = await caller.list({ level: 5, isActive: true });

    expect(findMany).toHaveBeenCalledWith({
      where: { level: 5, isActive: true },
      orderBy: [{ level: "asc" }, { sortOrder: "asc" }, { name: "asc" }],
    });
    expect(result).toHaveLength(1);
  });

  it("builds an org-unit tree through the router", async () => {
    const findMany = vi.fn().mockResolvedValue([
      {
        id: "ou_root",
        name: "Delivery",
        shortName: "DEL",
        level: 5,
        parentId: null,
        sortOrder: 10,
        isActive: true,
        createdAt: new Date("2026-03-01T00:00:00.000Z"),
        updatedAt: new Date("2026-03-01T00:00:00.000Z"),
      },
      {
        id: "ou_child",
        name: "Delivery Germany",
        shortName: "DE",
        level: 6,
        parentId: "ou_root",
        sortOrder: 20,
        isActive: true,
        createdAt: new Date("2026-03-01T00:00:00.000Z"),
        updatedAt: new Date("2026-03-01T00:00:00.000Z"),
      },
    ]);

    const caller = createProtectedCaller({
      orgUnit: { findMany },
    }, {
      granted: [PermissionKey.MANAGE_RESOURCES],
    });
    const result = await caller.getTree({ isActive: true });

    expect(findMany).toHaveBeenCalledWith({
      where: { isActive: true },
      orderBy: [{ sortOrder: "asc" }, { name: "asc" }],
    });
    expect(result).toEqual([
      expect.objectContaining({
        id: "ou_root",
        children: [expect.objectContaining({ id: "ou_child" })],
      }),
    ]);
  });

  it("creates and deactivates org units through the admin router", async () => {
    const findUnique = vi.fn().mockResolvedValue({
      id: "ou_root",
      level: 5,
      name: "Delivery",
    });
    const create = vi.fn().mockResolvedValue({
      id: "ou_child",
      name: "Delivery Germany",
      level: 6,
      parentId: "ou_root",
      sortOrder: 20,
    });
    const update = vi.fn().mockResolvedValue({
      id: "ou_child",
      name: "Delivery Germany",
      isActive: false,
    });

    const caller = createProtectedCaller({
      orgUnit: { findUnique, create, update },
    }, {
      role: SystemRole.ADMIN,
    });

    const created = await caller.create({
      name: "Delivery Germany",
      level: 6,
      parentId: "ou_root",
      sortOrder: 20,
    });
    const deactivated = await caller.deactivate({ id: "ou_child" });

    expect(create).toHaveBeenCalledWith({
      data: {
        name: "Delivery Germany",
        level: 6,
        parentId: "ou_root",
        sortOrder: 20,
      },
    });
    expect(update).toHaveBeenCalledWith({
      where: { id: "ou_child" },
      data: { isActive: false },
    });
    expect(created.id).toBe("ou_child");
    expect(deactivated.isActive).toBe(false);
    expect(createAuditEntry).toHaveBeenCalledTimes(2);
  });
});
