import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import { getCurrency } from "../../primitives/query/getCurrency.generated";
import type { Namespace } from "../generated/kysely-tailordb";
import { InvalidLegalNameError, CurrencyNotFoundError } from "../lib/errors.generated";
import { draftCompany } from "../testing/fixtures";
import { run } from "./createCompany";

const ctx: CommandContext = {
  actorId: "test-actor",
  permissions: ["organization:organization:createCompany"],
};

describe("createCompany", () => {
  it("creates company in DRAFT status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activeCurrency = { id: "currency-usd", status: "ACTIVE" as const };
    const createdCompany = { ...draftCompany, id: "new-company-id" };
    mock.enqueueResults(
      [activeCurrency], // getCurrency lookup
      [createdCompany],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          legalName: "Acme Corp",
          baseCurrencyId: "currency-usd",
        },
        ctx,
        { getCurrency },
      ),
    );

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

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

    const result = await mock.withTx((trx) => run(trx, { legalName: "" }, ctx));

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

  it("throws when referenced currency does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]); // getCurrency lookup returns null

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          legalName: "Acme Corp",
          baseCurrencyId: "nonexistent-currency",
        },
        ctx,
        { getCurrency },
      ),
    );

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

  it("throws when referenced currency is inactive", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ id: "inactive-currency", status: "INACTIVE" as const }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          legalName: "Acme Corp",
          baseCurrencyId: "inactive-currency",
        },
        ctx,
        { getCurrency },
      ),
    );

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

  it("creates company without base currency", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdCompany = {
      ...draftCompany,
      id: "new-company-id",
      baseCurrencyId: null,
    };
    mock.enqueueResults([createdCompany]);

    const result = await mock.withTx((trx) => run(trx, { legalName: "Acme Corp" }, ctx));

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

  it("creates company with full address fields", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const activeCurrency = { id: "currency-usd", status: "ACTIVE" as const };
    const createdCompany = { ...draftCompany, id: "new-company-id" };
    mock.enqueueResults([activeCurrency], [createdCompany]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          legalName: "Acme Corp",
          baseCurrencyId: "currency-usd",
          taxId: "TAX-12345",
          registrationNumber: "REG-67890",
          street: "123 Main St",
          city: "Tokyo",
          state: "Tokyo",
          postalCode: "100-0001",
          country: "JP",
        },
        ctx,
        { getCurrency },
      ),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.company).toBeDefined();
    }
  });

  it("passes custom fields through to insert", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdCompany = { ...draftCompany, id: "new-company-id", customField: "value" };
    mock.enqueueResults([createdCompany]);

    await mock.withTx((trx) =>
      run(
        trx,
        {
          legalName: "Acme Corp",
          customField: "value",
        },
        ctx,
      ),
    );

    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({ customField: "value" }),
    );
  });
});
