import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  DepartmentNotFoundError,
  InvalidNameError,
  SelfReferenceError,
  ParentNotFoundError,
  CircularReferenceError,
} from "../lib/errors.generated";
import {
  activeDepartment,
  childDepartment,
  grandchildDepartment,
  inactiveDepartment,
  otherCompanyDepartment,
} from "../testing/fixtures";
import { run } from "./updateDepartment";

describe("updateDepartment", () => {
  it("updates department name", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = { ...activeDepartment, name: "New Name", updatedAt: new Date() };

    mock.enqueueResults(
      [activeDepartment], // find department
      [updated],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.department.name).toBe("New Name");
    }
  });

  it("updates parent department", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const newParent = {
      ...inactiveDepartment,
      status: "ACTIVE",
      companyId: activeDepartment.companyId,
    };
    const updated = {
      ...childDepartment,
      parentDepartmentId: newParent.id,
      updatedAt: new Date(),
    };

    mock.enqueueResults(
      [childDepartment], // find department
      [newParent], // find new parent
      [newParent], // ancestor walk: newParent has no parent
      [updated],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.department.parentDepartmentId).toBe(newParent.id);
    }
  });

  it("removes parent department (promotes to top-level)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updated = {
      ...childDepartment,
      parentDepartmentId: null,
      updatedAt: new Date(),
    };

    mock.enqueueResults(
      [childDepartment], // find department
      [updated],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.department.parentDepartmentId).toBeNull();
    }
  });

  it("returns error 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",
        name: "New Name",
      }),
    );

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

  it("returns error when name is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activeDepartment]);

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

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

  it("returns error when name is whitespace-only", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activeDepartment]);

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

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

  it("returns error when setting self as parent", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([activeDepartment]);

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

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

  it("returns error when parent does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [activeDepartment], // find department
      [], // parent not found
    );

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

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

  it("returns error when parent belongs to different company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [activeDepartment], // find department
      [otherCompanyDepartment], // parent in different company
    );

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

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

  it("returns error when reparenting creates circular reference", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    // activeDepartment -> childDepartment -> grandchildDepartment
    // Try to set activeDepartment's parent to grandchildDepartment
    // Ancestor walk: grandchildDepartment -> childDepartment (parentDepartmentId=dept-1) -> activeDepartment.id found!
    mock.enqueueResults(
      [activeDepartment], // find department (activeDepartment)
      [grandchildDepartment], // find parent (grandchildDepartment)
      [grandchildDepartment], // ancestor walk: start at grandchildDepartment
      [childDepartment], // ancestor walk: grandchild's parent is childDepartment, whose parentDepartmentId is dept-1 === departmentId
    );

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

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

  it("updates parent on INACTIVE department", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const newParent = { ...activeDepartment };
    const updated = {
      ...inactiveDepartment,
      parentDepartmentId: newParent.id,
      updatedAt: new Date(),
    };

    mock.enqueueResults(
      [inactiveDepartment], // find department
      [newParent], // find new parent
      [newParent], // ancestor walk: newParent has no parent
      [updated],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.department.parentDepartmentId).toBe(newParent.id);
    }
  });
});
