import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } 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 { db, spies } = createMockDb<Transaction>();
    const updated = { ...activeDepartment, name: "New Name", updatedAt: new Date() };

    spies.select.mockReturnValueOnce(activeDepartment); // find department
    spies.update.mockReturnValue(updated);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    const newParent = {
      ...inactiveDepartment,
      status: "ACTIVE",
      companyId: activeDepartment.companyId,
    };
    const updated = {
      ...childDepartment,
      parentDepartmentId: newParent.id,
      updatedAt: new Date(),
    };

    spies.select
      .mockReturnValueOnce(childDepartment) // find department
      .mockReturnValueOnce(newParent) // find new parent
      .mockReturnValueOnce(newParent); // ancestor walk: newParent has no parent
    spies.update.mockReturnValue(updated);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    const updated = {
      ...childDepartment,
      parentDepartmentId: null,
      updatedAt: new Date(),
    };

    spies.select.mockReturnValueOnce(childDepartment); // find department
    spies.update.mockReturnValue(updated);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValue(undefined);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activeDepartment);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activeDepartment);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(activeDepartment);

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(activeDepartment) // find department
      .mockReturnValueOnce(undefined); // parent not found

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(activeDepartment) // find department
      .mockReturnValueOnce(otherCompanyDepartment); // parent in different company

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    // activeDepartment -> childDepartment -> grandchildDepartment
    // Try to set activeDepartment's parent to grandchildDepartment
    // Ancestor walk: grandchildDepartment -> childDepartment (parentDepartmentId=dept-1) -> activeDepartment.id found!
    spies.select
      .mockReturnValueOnce(activeDepartment) // find department (activeDepartment)
      .mockReturnValueOnce(grandchildDepartment) // find parent (grandchildDepartment)
      .mockReturnValueOnce(grandchildDepartment) // ancestor walk: start at grandchildDepartment
      .mockReturnValueOnce(childDepartment); // ancestor walk: grandchild's parent is childDepartment, whose parentDepartmentId is dept-1 === departmentId

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    const newParent = { ...activeDepartment };
    const updated = {
      ...inactiveDepartment,
      parentDepartmentId: newParent.id,
      updatedAt: new Date(),
    };

    spies.select
      .mockReturnValueOnce(inactiveDepartment) // find department
      .mockReturnValueOnce(newParent) // find new parent
      .mockReturnValueOnce(newParent); // ancestor walk: newParent has no parent
    spies.update.mockReturnValue(updated);

    const result = await run(db, {
      departmentId: inactiveDepartment.id,
      parentDepartmentId: newParent.id,
    });

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