import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  AccountGroupNotFoundError,
  ChartOfAccountsArchivedError,
  ParentGroupNotFoundError,
  CircularReferenceError,
} from "../lib/errors.generated";
import {
  baseActiveCoa,
  baseArchivedCoa,
  baseRootGroup,
  baseChildGroup,
  baseGrandchildGroup,
  baseGroupNoRange,
} from "../testing/fixtures";
import { run } from "./moveAccountGroup";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

const ctx: CommandContext = {
  actorId: "test-actor",
  permissions: ["coa-management:moveAccountGroup"],
};

describe("moveAccountGroup", () => {
  it("returns error when group does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // Group lookup

    const result = await run(db, { id: "nonexistent", newParentAccountGroupId: null }, ctx);

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

  it("returns error when parent CoA is ARCHIVED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const groupInArchivedCoa = { ...baseRootGroup, chartOfAccountsId: baseArchivedCoa.id };
    spies.select
      .mockReturnValueOnce(groupInArchivedCoa) // Group lookup
      .mockReturnValueOnce(baseArchivedCoa); // CoA lookup

    const result = await run(db, { id: groupInArchivedCoa.id, newParentAccountGroupId: null }, ctx);

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

  it("returns error when new parent does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseChildGroup) // Group lookup
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined); // New parent not found

    const result = await run(
      db,
      { id: baseChildGroup.id, newParentAccountGroupId: "nonexistent" },
      ctx,
    );

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

  it("returns error when new parent belongs to different CoA", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const parentInDifferentCoa = { ...baseGroupNoRange, chartOfAccountsId: "other-coa" };
    spies.select
      .mockReturnValueOnce(baseChildGroup) // Group lookup
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(parentInDifferentCoa); // New parent in different CoA

    const result = await run(
      db,
      { id: baseChildGroup.id, newParentAccountGroupId: parentInDifferentCoa.id },
      ctx,
    );

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

  it("returns error when moving group under itself", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseRootGroup) // Group lookup
      .mockReturnValueOnce(baseActiveCoa); // CoA lookup

    const result = await run(
      db,
      { id: baseRootGroup.id, newParentAccountGroupId: baseRootGroup.id },
      ctx,
    );

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

  it("returns error when moving group under its descendant", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // Scenario: move group-1 (root) under group-3 (grandchild of group-1)
    // group-1 -> group-2 -> group-3
    // Walk up from group-3's parent chain: group-3.parent = group-2, group-2.parent = group-1 (the group being moved)
    spies.select
      .mockReturnValueOnce(baseRootGroup) // Group lookup (group-1)
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(baseGrandchildGroup) // New parent lookup (group-3)
      .mockReturnValueOnce(baseChildGroup); // Walking up: group-3.parent = group-2, then group-2.parent = group-1 (circular!)

    const result = await run(
      db,
      { id: baseRootGroup.id, newParentAccountGroupId: baseGrandchildGroup.id },
      ctx,
    );

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

  it("moves group to different parent", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const movedGroup = { ...baseChildGroup, parentAccountGroupId: baseGroupNoRange.id };
    spies.select
      .mockReturnValueOnce(baseChildGroup) // Group lookup
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(baseGroupNoRange); // New parent lookup (root, no further ancestors)
    spies.update.mockReturnValue(movedGroup);

    const result = await run(
      db,
      { id: baseChildGroup.id, newParentAccountGroupId: baseGroupNoRange.id },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountGroup.parentAccountGroupId).toBe(baseGroupNoRange.id);
      expect(result.value.previousParentAccountGroupId).toBe(baseRootGroup.id);
    }
  });

  it("promotes group to root by setting parent to null", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const movedGroup = { ...baseChildGroup, parentAccountGroupId: null };
    spies.select
      .mockReturnValueOnce(baseChildGroup) // Group lookup
      .mockReturnValueOnce(baseActiveCoa); // CoA lookup
    spies.update.mockReturnValue(movedGroup);

    const result = await run(db, { id: baseChildGroup.id, newParentAccountGroupId: null }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountGroup.parentAccountGroupId).toBeNull();
      expect(result.value.previousParentAccountGroupId).toBe(baseRootGroup.id);
    }
  });
});
