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

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

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

    const result = await run(
      db,
      {
        chartOfAccountsId: "nonexistent",
        code: "1000",
        name: "Assets",
      },
      ctx,
    );

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

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

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

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

  it("returns error when group code already exists in CoA", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(baseRootGroup); // Duplicate code check

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: baseRootGroup.code,
        name: "Duplicate Code Group",
      },
      ctx,
    );

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

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

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

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

    // Also rejects blank (whitespace-only) codes
    const { db: db2, spies: spies2 } = createMockDb<Transaction>();
    spies2.select.mockReturnValueOnce(baseActiveCoa);

    const result2 = await run(
      db2,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "   ",
        name: "Assets",
      },
      ctx,
    );

    expect(result2.ok).toBe(false);
    if (!result2.ok) {
      expect(result2.error).toBeInstanceOf(CodeRequiredError);
    }
  });

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

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "3000",
        name: "",
      },
      ctx,
    );

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

  it("returns error when parent group does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined) // No duplicate code
      .mockReturnValueOnce(undefined); // Parent group not found

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "3000",
        name: "Revenue",
        parentAccountGroupId: "nonexistent",
      },
      ctx,
    );

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

  it("returns error when parent group belongs to different CoA", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const parentInDifferentCoa = { ...baseRootGroup, chartOfAccountsId: "other-coa" };
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined) // No duplicate code
      .mockReturnValueOnce(parentInDifferentCoa); // Parent in different CoA

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "3000",
        name: "Revenue",
        parentAccountGroupId: parentInDifferentCoa.id,
      },
      ctx,
    );

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

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

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "3000",
        name: "Revenue",
        numberRangeStart: 3000,
        numberRangeEnd: 2000,
      },
      ctx,
    );

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

  it("returns error when only numberRangeStart is provided", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined); // No duplicate code

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "3000",
        name: "Revenue",
        numberRangeStart: 3000,
      },
      ctx,
    );

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

  it("returns error when only numberRangeEnd is provided", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined); // No duplicate code

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "3000",
        name: "Revenue",
        numberRangeEnd: 3999,
      },
      ctx,
    );

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

  it("returns error when number range overlaps with existing group", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined) // No duplicate code
      .mockReturnValueOnce([baseRootGroup]); // Existing groups with overlapping range

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1500",
        name: "Overlapping Range",
        numberRangeStart: 1500,
        numberRangeEnd: 2500,
      },
      ctx,
    );

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

  it("creates a root group with no parent", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdGroup = {
      ...baseRootGroup,
      id: "new-group-id",
      code: "3000",
      name: "Revenue",
      parentAccountGroupId: null,
    };
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined); // No duplicate code
    spies.insert.mockReturnValue(createdGroup);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "3000",
        name: "Revenue",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.accountGroup.code).toBe("3000");
      expect(result.value.accountGroup.parentAccountGroupId).toBeNull();
    }
  });

  it("creates a child group with valid parent", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdGroup = {
      ...baseChildGroup,
      id: "new-child-id",
      code: "1200",
      name: "Fixed Assets",
      parentAccountGroupId: baseRootGroup.id,
    };
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined) // No duplicate code
      .mockReturnValueOnce(baseRootGroup); // Parent group lookup
    spies.insert.mockReturnValue(createdGroup);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1200",
        name: "Fixed Assets",
        parentAccountGroupId: baseRootGroup.id,
      },
      ctx,
    );

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

  it("creates a group with account number range", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdGroup = {
      ...baseRootGroup,
      id: "new-group-id",
      code: "3000",
      name: "Revenue",
      numberRangeStart: 3000,
      numberRangeEnd: 3999,
    };
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined) // No duplicate code
      .mockReturnValueOnce([]); // No overlapping groups
    spies.insert.mockReturnValue(createdGroup);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "3000",
        name: "Revenue",
        numberRangeStart: 3000,
        numberRangeEnd: 3999,
      },
      ctx,
    );

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

  it("creates a group with sort order", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdGroup = {
      ...baseRootGroup,
      id: "new-group-id",
      code: "3000",
      name: "Revenue",
      sortOrder: 5,
    };
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined); // No duplicate code
    spies.insert.mockReturnValue(createdGroup);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "3000",
        name: "Revenue",
        sortOrder: 5,
      },
      ctx,
    );

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

  it("passes custom fields through to insert", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const createdGroup = {
      ...baseRootGroup,
      id: "new-group-id",
      customField: "custom-value",
    };
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined); // No duplicate code
    spies.insert.mockReturnValue(createdGroup);

    await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "5000",
        name: "Custom Group",
        customField: "custom-value",
      },
      ctx,
    );

    expect(spies.values).toHaveBeenNthCalledWith(
      1,
      expect.objectContaining({ customField: "custom-value" }),
    );
  });
});
