import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  DepartmentNotFoundError,
  InvalidStateError,
  HasActiveChildrenError,
} from "../lib/errors.generated";
import { activeDepartment, inactiveDepartment } from "../testing/fixtures";
import { run } from "./deactivateDepartment";

describe("deactivateDepartment", () => {
  it("deactivates ACTIVE department with no sub-departments", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivated = {
      ...activeDepartment,
      status: "INACTIVE",
      updatedAt: new Date(),
    };

    mock.enqueueResults(
      [activeDepartment], // find department
      [], // no active children
      [deactivated],
    );

    const result = await mock.withTx((trx) =>
      run(trx, {
        departmentId: activeDepartment.id,
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.department.status).toBe("INACTIVE");
      expect(result.value.department.updatedAt).not.toBeNull();
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("deactivates ACTIVE department with only INACTIVE sub-departments", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const deactivated = {
      ...activeDepartment,
      status: "INACTIVE",
      updatedAt: new Date(),
    };

    mock.enqueueResults(
      [activeDepartment], // find department
      [], // no ACTIVE children (only inactive ones)
      [deactivated],
    );

    const result = await mock.withTx((trx) =>
      run(trx, {
        departmentId: activeDepartment.id,
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.department.status).toBe("INACTIVE");
    }
  });

  it("throws when department does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        departmentId: "nonexistent-dept",
      }),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(DepartmentNotFoundError);
    }
  });

  it("throws when department is already INACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([inactiveDepartment]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        departmentId: inactiveDepartment.id,
      }),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStateError);
    }
  });

  it("throws when department has active sub-departments", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activeChild = {
      id: "child-dept",
      code: "CHILD",
      name: "Child Dept",
      companyId: activeDepartment.companyId,
      parentDepartmentId: activeDepartment.id,
      status: "ACTIVE",
      createdAt: new Date(),
      updatedAt: null,
    };

    mock.enqueueResults(
      [activeDepartment], // find department
      [activeChild], // active child found
    );

    const result = await mock.withTx((trx) =>
      run(trx, {
        departmentId: activeDepartment.id,
      }),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(HasActiveChildrenError);
    }
  });
});
