import { TRPCError } from "@trpc/server";
import { describe, expect, it, vi } from "vitest";
import {
  assertOrgUnitParentLevel,
  buildOrgUnitCreateData,
  buildOrgUnitListWhere,
  buildOrgUnitTree,
  buildOrgUnitUpdateData,
  findOrgUnitByIdentifier,
} from "../router/org-unit-support.js";

describe("org-unit support", () => {
  it("builds list filters", () => {
    expect(buildOrgUnitListWhere({
      level: 5,
      parentId: "root",
      isActive: true,
    })).toEqual({
      level: 5,
      parentId: "root",
      isActive: true,
    });
  });

  it("builds a sorted org-unit tree", () => {
    expect(buildOrgUnitTree([
      {
        id: "child_b",
        name: "Beta",
        shortName: "BET",
        level: 6,
        parentId: "root",
        sortOrder: 20,
        isActive: true,
        createdAt: new Date("2026-03-01T00:00:00.000Z"),
        updatedAt: new Date("2026-03-01T00:00:00.000Z"),
      },
      {
        id: "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: "child_a",
        name: "Alpha",
        shortName: "ALP",
        level: 6,
        parentId: "root",
        sortOrder: 20,
        isActive: true,
        createdAt: new Date("2026-03-01T00:00:00.000Z"),
        updatedAt: new Date("2026-03-01T00:00:00.000Z"),
      },
    ])).toEqual([
      expect.objectContaining({
        id: "root",
        children: [
          expect.objectContaining({ id: "child_a", children: [] }),
          expect.objectContaining({ id: "child_b", children: [] }),
        ],
      }),
    ]);
  });

  it("resolves org units by short name fallback", async () => {
    const db = {
      orgUnit: {
        findUnique: vi.fn().mockResolvedValue(null),
        findFirst: vi.fn()
          .mockResolvedValueOnce(null)
          .mockResolvedValueOnce({ id: "ou_1", shortName: "DEL" }),
      },
    } as never;

    const result = await findOrgUnitByIdentifier<{ id: string; shortName: string }>(
      db,
      " del ",
      { select: { id: true, shortName: true } },
    );

    expect(result).toEqual({ id: "ou_1", shortName: "DEL" });
    expect(db.orgUnit.findFirst).toHaveBeenNthCalledWith(2, {
      where: { shortName: { equals: "del", mode: "insensitive" } },
      select: { id: true, shortName: true },
    });
  });

  it("rejects invalid parent/child level combinations", () => {
    expect(() => assertOrgUnitParentLevel({ level: 6 }, 6)).toThrow(TRPCError);
  });

  it("builds create and sparse update payloads", () => {
    expect(buildOrgUnitCreateData({
      name: "Delivery",
      shortName: "DEL",
      level: 5,
      parentId: "root",
      sortOrder: 10,
    })).toEqual({
      name: "Delivery",
      shortName: "DEL",
      level: 5,
      parentId: "root",
      sortOrder: 10,
    });

    expect(buildOrgUnitUpdateData({
      shortName: null,
      isActive: false,
    })).toEqual({
      shortName: null,
      isActive: false,
    });
  });
});
