import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  ChartOfAccountsNotFoundError,
  DuplicateAccountCodeError,
  IncompatibleClassificationError,
  DuplicateRetainedEarningsError,
  CurrencyNotFoundError,
  AccountGroupNotFoundError,
  CodeOutOfRangeError,
  NameRequiredError,
  InvalidAccountCodeError,
  ReconciliationRequiredError,
} from "../lib/errors.generated";
import {
  baseActiveCoa,
  baseArchivedCoa,
  baseDraftAccount,
  baseRetainedEarningsAccount,
  baseRootGroup,
  baseChildGroup,
} from "../testing/fixtures";
import { run, type CreateAccountInput } from "./createAccount";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

const mockGetCurrency = {
  getCurrency: (_db: Transaction, input: { id: string }, _ctx: CommandContext) =>
    Promise.resolve({
      ok: true as const,
      value: { currency: { id: input.id, isActive: true } },
    }),
};

const mockGetCurrencyNotFound = {
  getCurrency: (_db: Transaction, _input: { id: string }, _ctx: CommandContext) =>
    Promise.resolve({
      ok: true as const,
      value: { currency: null },
    }),
};

describe("createAccount", () => {
  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: "1100",
        name: "Cash",
        accountType: "ASSET",
      },
      ctx,
    );

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

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

    const result = await run(
      db,
      {
        chartOfAccountsId: baseArchivedCoa.id,
        code: "1100",
        name: "Cash",
        accountType: "ASSET",
      },
      ctx,
    );

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

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

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

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

  it("returns error when account code is not a valid numeric identifier", async () => {
    const { db } = createMockDb<Transaction>();

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

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

  it("returns error when name is empty", async () => {
    const { db } = createMockDb<Transaction>();

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

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

  it("returns error when classification is incompatible with type", 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: "1100",
        name: "Cash",
        accountType: "LIABILITY",
        classification: "RECEIVABLE", // requires ASSET
      },
      ctx,
    );

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

  it("returns error when RETAINED_EARNINGS already exists in CoA", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined) // no duplicate code
      .mockReturnValueOnce(baseRetainedEarningsAccount); // existing retained earnings

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "3200",
        name: "Another Retained Earnings",
        accountType: "EQUITY",
        classification: "RETAINED_EARNINGS",
      },
      ctx,
    );

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

  it("returns error when currency does not exist", 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: "1100",
        name: "Cash",
        accountType: "ASSET",
        currencyRestriction: "nonexistent-currency",
      },
      ctx,
      mockGetCurrencyNotFound,
    );

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

  it("returns error when account group belongs to different CoA", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const differentCoaGroup = { ...baseRootGroup, chartOfAccountsId: "coa-999" };
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined) // no duplicate code
      .mockReturnValueOnce(differentCoaGroup); // group lookup (different CoA)

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1100",
        name: "Cash",
        accountType: "ASSET",
        accountGroupId: differentCoaGroup.id,
      },
      ctx,
    );

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

  it("returns error when account code is outside group number range", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined) // no duplicate code
      .mockReturnValueOnce(baseChildGroup); // group lookup (range 1100-1199)

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "9999",
        name: "Cash",
        accountType: "ASSET",
        accountGroupId: baseChildGroup.id,
      },
      ctx,
    );

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

  it("creates account in DRAFT status with defaults", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      code: "1500",
      name: "New Account",
    };
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined); // no duplicate code
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1500",
        name: "New Account",
        accountType: "ASSET",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.status).toBe("DRAFT");
    }
  });

  it("creates account with RECEIVABLE classification and enforces reconciliation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      classification: "RECEIVABLE",
      reconciliation: true,
    };
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1100",
        name: "AR",
        accountType: "ASSET",
        classification: "RECEIVABLE",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.reconciliation).toBe(true);
    }
  });

  it("creates account with PAYABLE classification and enforces reconciliation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      classification: "PAYABLE",
      accountType: "LIABILITY",
      reconciliation: true,
    };
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "2100",
        name: "AP",
        accountType: "LIABILITY",
        classification: "PAYABLE",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.reconciliation).toBe(true);
    }
  });

  it("creates account with BANK_CASH classification and enforces reconciliation", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      classification: "BANK_CASH",
      reconciliation: true,
    };
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1100",
        name: "Bank",
        accountType: "ASSET",
        classification: "BANK_CASH",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.reconciliation).toBe(true);
    }
  });

  it("creates NON_POSTING account that is marked as excluded from journal entry posting", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      classification: "NON_POSTING",
    };
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1100",
        name: "Statistical",
        accountType: "ASSET",
        classification: "NON_POSTING",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.classification).toBe("NON_POSTING");
    }
  });

  it("creates RECEIVABLE account that is marked as control account blocking manual postings", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      classification: "RECEIVABLE",
      reconciliation: true,
    };
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1100",
        name: "AR Control",
        accountType: "ASSET",
        classification: "RECEIVABLE",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.classification).toBe("RECEIVABLE");
    }
  });

  it("creates PAYABLE account that is marked as control account blocking manual postings", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      classification: "PAYABLE",
      accountType: "LIABILITY",
      reconciliation: true,
    };
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "2100",
        name: "AP Control",
        accountType: "LIABILITY",
        classification: "PAYABLE",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.classification).toBe("PAYABLE");
    }
  });

  it("creates account with currency restriction that constrains posting currency", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      currencyRestriction: "currency-usd",
    };
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined); // no duplicate code
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1100",
        name: "USD Account",
        accountType: "ASSET",
        currencyRestriction: "currency-usd",
      },
      ctx,
      mockGetCurrency,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.currencyRestriction).toBe("currency-usd");
    }
  });

  it("creates account with optional currency restriction", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      currencyRestriction: "currency-eur",
    };
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1100",
        name: "EUR Account",
        accountType: "ASSET",
        currencyRestriction: "currency-eur",
      },
      ctx,
      mockGetCurrency,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.currencyRestriction).toBe("currency-eur");
    }
  });

  it("creates account with optional tags", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      tags: "tag1,tag2",
    };
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1100",
        name: "Tagged Account",
        accountType: "ASSET",
        tags: "tag1,tag2",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.tags).toBe("tag1,tag2");
    }
  });

  it("creates account with optional default tax code", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      defaultTaxCode: "VAT20",
    };
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1100",
        name: "Tax Account",
        accountType: "ASSET",
        defaultTaxCode: "VAT20",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.defaultTaxCode).toBe("VAT20");
    }
  });

  it("creates account assigned to a group", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      code: "1150",
      accountGroupId: baseChildGroup.id,
    };
    spies.select
      .mockReturnValueOnce(baseActiveCoa) // CoA lookup
      .mockReturnValueOnce(undefined) // no duplicate code
      .mockReturnValueOnce(baseChildGroup); // group lookup
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1150",
        name: "Grouped Account",
        accountType: "ASSET",
        accountGroupId: baseChildGroup.id,
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.accountGroupId).toBe(baseChildGroup.id);
    }
  });

  it("defaults classification to REGULAR when not specified", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      classification: "REGULAR",
    };
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1100",
        name: "Regular Account",
        accountType: "ASSET",
      },
      ctx,
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.classification).toBe("REGULAR");
    }
  });

  it("returns error when reconciliation explicitly set to false for RECEIVABLE classification", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1100",
        name: "AR",
        accountType: "ASSET",
        classification: "RECEIVABLE",
        reconciliation: false,
      },
      ctx,
    );

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

  it("returns error when reconciliation explicitly set to false for PAYABLE classification", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "2100",
        name: "AP",
        accountType: "LIABILITY",
        classification: "PAYABLE",
        reconciliation: false,
      },
      ctx,
    );

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

  it("returns error when reconciliation explicitly set to false for BANK_CASH classification", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1100",
        name: "Bank",
        accountType: "ASSET",
        classification: "BANK_CASH",
        reconciliation: false,
      },
      ctx,
    );

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

  it("passes custom fields through to insert", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = {
      ...baseDraftAccount,
      customField: "custom-value",
    };
    spies.select.mockReturnValueOnce(baseActiveCoa).mockReturnValueOnce(undefined);
    spies.insert.mockReturnValue(created);

    const result = await run(
      db,
      {
        chartOfAccountsId: baseActiveCoa.id,
        code: "1100",
        name: "Custom Account",
        accountType: "ASSET",
        customField: "custom-value",
      } as CreateAccountInput & { customField: string },
      ctx,
    );

    expect(result.ok).toBe(true);
    expect(spies.values).toHaveBeenCalled();
    const insertedValues = spies.values.mock.calls[0][0] as Record<string, unknown>;
    expect(insertedValues.customField).toBe("custom-value");
  });
});
