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

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

describe("updateAccountGroup", () => {
  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", name: "New Name" }, 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, name: "New Name" }, ctx);

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

  it("looks up group by chartOfAccountsId and code and updates name", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedGroup = { ...baseRootGroup, name: "Lookup Assets" };
    spies.select.mockReturnValueOnce(baseRootGroup).mockReturnValueOnce(baseActiveCoa);
    spies.update.mockReturnValue(updatedGroup);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseRootGroup.chartOfAccountsId,
        code: baseRootGroup.code,
        name: "Lookup Assets",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountGroup.name).toBe("Lookup Assets");
    }
  });

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

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

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

  it("returns error when new number range is invalid", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseRootGroup) // Group lookup
      .mockReturnValueOnce(baseActiveCoa); // CoA lookup

    const result = await run(
      db,
      { id: baseRootGroup.id, numberRangeStart: 2000, numberRangeEnd: 1000 },
      ctx,
    );

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

  it("returns error when updating to one-sided number range (start only)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const groupNoRange = { ...baseGroupNoRange };
    spies.select
      .mockReturnValueOnce(groupNoRange) // Group lookup
      .mockReturnValueOnce(baseActiveCoa); // CoA lookup

    const result = await run(db, { id: groupNoRange.id, numberRangeStart: 2000 }, ctx);

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

  it("returns error when updating to one-sided number range (end only)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const groupNoRange = { ...baseGroupNoRange };
    spies.select
      .mockReturnValueOnce(groupNoRange) // Group lookup
      .mockReturnValueOnce(baseActiveCoa); // CoA lookup

    const result = await run(db, { id: groupNoRange.id, numberRangeEnd: 2999 }, ctx);

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

  it("returns error when new number range overlaps with another group", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const otherGroup = { ...baseGroupNoRange, numberRangeStart: 2000, numberRangeEnd: 2999 };
    spies.select
      .mockReturnValueOnce(baseRootGroup) // Group lookup
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce([baseRootGroup, otherGroup]) // Existing groups for overlap check
      .mockReturnValueOnce([]); // No assigned accounts

    const result = await run(
      db,
      { id: baseRootGroup.id, numberRangeStart: 1500, numberRangeEnd: 2500 },
      ctx,
    );

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

  it("returns error when existing accounts fall outside new number range", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const groupWithRange = { ...baseChildGroup, id: "group-with-accounts" };
    const accountOutOfRange = {
      ...baseActiveAccount,
      code: "1500",
      accountGroupId: "group-with-accounts",
    };
    spies.select
      .mockReturnValueOnce(groupWithRange) // Group lookup
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce([groupWithRange]) // Existing groups (only self, no overlap)
      .mockReturnValueOnce([accountOutOfRange]); // Assigned accounts out of new range

    const result = await run(
      db,
      { id: groupWithRange.id, numberRangeStart: 1100, numberRangeEnd: 1199 },
      ctx,
    );

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

  it("updates group name", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedGroup = { ...baseRootGroup, name: "Updated Assets" };
    spies.select
      .mockReturnValueOnce(baseRootGroup) // Group lookup
      .mockReturnValueOnce(baseActiveCoa); // CoA lookup
    spies.update.mockReturnValue(updatedGroup);

    const result = await run(db, { id: baseRootGroup.id, name: "Updated Assets" }, ctx);

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountGroup.name).toBe("Updated Assets");
    }
  });

  it("updates sort order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedGroup = { ...baseRootGroup, sortOrder: 10 };
    spies.select
      .mockReturnValueOnce(baseRootGroup) // Group lookup
      .mockReturnValueOnce(baseActiveCoa); // CoA lookup
    spies.update.mockReturnValue(updatedGroup);

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountGroup.sortOrder).toBe(10);
    }
  });

  it("updates number range", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedGroup = { ...baseRootGroup, numberRangeStart: 1000, numberRangeEnd: 1499 };
    spies.select
      .mockReturnValueOnce(baseRootGroup) // Group lookup
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce([baseRootGroup]) // Existing groups (only self)
      .mockReturnValueOnce([]); // No assigned accounts
    spies.update.mockReturnValue(updatedGroup);

    const result = await run(
      db,
      { id: baseRootGroup.id, numberRangeStart: 1000, numberRangeEnd: 1499 },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountGroup.numberRangeStart).toBe(1000);
      expect(result.value.accountGroup.numberRangeEnd).toBe(1499);
    }
  });

  it("passes custom fields through to update", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedGroup = { ...baseRootGroup, customField: "custom-value" };
    spies.select
      .mockReturnValueOnce(baseRootGroup) // Group lookup
      .mockReturnValueOnce(baseActiveCoa); // CoA lookup
    spies.update.mockReturnValue(updatedGroup);

    await run(db, { id: baseRootGroup.id, name: "Updated", customField: "custom-value" }, ctx);

    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ customField: "custom-value" }),
    );
  });
});
