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

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

describe("createCompany", () => {
  it("creates company in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activeCurrency = { id: "currency-usd", isActive: true };
    const createdCompany = { ...draftCompany, id: "new-company-id" };
    spies.select.mockReturnValueOnce(activeCurrency); // getCurrency lookup
    spies.insert.mockReturnValue(createdCompany);

    const result = await run(
      db,
      {
        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 { db } = createMockDb<Transaction>();

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // getCurrency lookup returns null

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ id: "inactive-currency", isActive: false });

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    const createdCompany = {
      ...draftCompany,
      id: "new-company-id",
      baseCurrencyId: null,
    };
    spies.insert.mockReturnValue(createdCompany);

    const result = await run(db, { 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 { db, spies } = createMockDb<Transaction>();
    const activeCurrency = { id: "currency-usd", isActive: true };
    const createdCompany = { ...draftCompany, id: "new-company-id" };
    spies.select.mockReturnValueOnce(activeCurrency);
    spies.insert.mockReturnValue(createdCompany);

    const result = await run(
      db,
      {
        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 { db, spies } = createMockDb<Transaction>();
    const createdCompany = { ...draftCompany, id: "new-company-id", customField: "value" };
    spies.insert.mockReturnValue(createdCompany);

    await run(
      db,
      {
        legalName: "Acme Corp",
        customField: "value",
      },
      ctx,
    );

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