import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  CompanyInactiveError,
  CompanyNotFoundError,
  DuplicateAccountCodeError,
  InvalidAccountCodeError,
  NameRequiredError,
} from "../lib/errors.generated";
import { baseActiveAccount, baseActiveCompany } from "../testing/fixtures";
import { run, type CreateAccountInput } from "./createAccount";

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

const organizationQueries = {
  getCompany: () =>
    Promise.resolve({
      ok: true as const,
      value: { company: { ...baseActiveCompany, status: "ACTIVE" as const } },
    }),
};

const runCreate = (
  mock: ReturnType<typeof createKyselyMock<Namespace["main-db"]>>,
  input: CreateAccountInput & Record<string, unknown>,
) => mock.withTx((trx) => run(trx, input, ctx, organizationQueries));

describe("createAccount", () => {
  it("returns error when company does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const missingCompanyQueries = {
      getCompany: () =>
        Promise.resolve({
          ok: true as const,
          value: { company: null },
        }),
    };

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { companyId: "missing", code: "1100", name: "Cash", accountType: "ASSET" },
        ctx,
        missingCompanyQueries,
      ),
    );

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

  it("returns error when company is not ACTIVE", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const inactiveCompanyQueries = {
      getCompany: () =>
        Promise.resolve({
          ok: true as const,
          value: { company: { ...baseActiveCompany, status: "INACTIVE" as const } },
        }),
    };

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { companyId: baseActiveCompany.id, code: "1100", name: "Cash", accountType: "ASSET" },
        ctx,
        inactiveCompanyQueries,
      ),
    );

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

  it("returns error when account code is not numeric", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await runCreate(mock, {
      companyId: baseActiveCompany.id,
      code: "ABC",
      name: "Cash",
      accountType: "ASSET",
    });

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

  it("returns error when name is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await runCreate(mock, {
      companyId: baseActiveCompany.id,
      code: "1100",
      name: "",
      accountType: "ASSET",
    });

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

  it("returns error when account code already exists in company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveAccount]);

    const result = await runCreate(mock, {
      companyId: baseActiveCompany.id,
      code: baseActiveAccount.code,
      name: "Duplicate",
      accountType: "ASSET",
    });

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

  it("creates account in ACTIVE status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const created = { ...baseActiveAccount, id: "new-account", code: "1100", name: "Cash" };
    mock.enqueueResults([], [created]);

    const result = await runCreate(mock, {
      companyId: baseActiveCompany.id,
      code: "1100",
      name: "Cash",
      accountType: "ASSET",
    });

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.account.status).toBe("ACTIVE");
      expect(result.value.account.code).toBe("1100");
    }
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({
        companyId: baseActiveCompany.id,
        code: "1100",
        status: "ACTIVE",
      }),
    );
  });

  it("passes custom fields through to insert", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const created = {
      ...baseActiveAccount,
      id: "new-account",
      code: "1100",
      name: "Cash",
      localReportingCode: "JP-CASH",
    };
    mock.enqueueResults([], [created]);

    const result = await runCreate(mock, {
      companyId: baseActiveCompany.id,
      code: "1100",
      name: "Cash",
      accountType: "ASSET",
      localReportingCode: "JP-CASH",
    });

    expect(result.ok).toBe(true);
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({ localReportingCode: "JP-CASH" }),
    );
  });
});
