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

describe("createPartner", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["business-partner:partner:createPartner"],
  };

  it("creates partner in DRAFT status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const company = { id: "company-1" };
    const createdPartner = { ...baseDraftPartner, id: "new-partner-id" };
    mock.enqueueResults([company], [createdPartner]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { name: "Acme Corp", type: "ORGANIZATION", companyId: "company-1" },
        ctx,
        { getCompany },
        { getCurrency },
      ),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.partner.status).toBe("DRAFT");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("returns error when company not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]); // Company not found

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { name: "Acme Corp", type: "ORGANIZATION", companyId: "nonexistent" },
        ctx,
        { getCompany },
        { getCurrency },
      ),
    );

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

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { name: "", type: "ORGANIZATION", companyId: "company-1" },
        ctx,
        { getCompany },
        { getCurrency },
      ),
    );

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

  it("creates partner without preferred currency", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const company = { id: "company-1" };
    const createdPartner = { ...baseDraftPartner, id: "new-partner-id", preferredCurrencyId: null };
    mock.enqueueResults([company], [createdPartner]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { name: "Acme Corp", type: "ORGANIZATION", companyId: "company-1" },
        ctx,
        { getCompany },
        { getCurrency },
      ),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.partner.preferredCurrencyId).toBeNull();
    }
  });

  it("creates partner with preferred currency", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const company = { id: "company-1" };
    const currency = { id: "currency-usd", code: "USD" };
    const createdPartner = {
      ...baseDraftPartner,
      id: "new-partner-id",
      preferredCurrencyId: "currency-usd",
    };
    mock.enqueueResults([company], [currency], [createdPartner]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          name: "Acme Corp",
          type: "ORGANIZATION",
          companyId: "company-1",
          preferredCurrencyId: "currency-usd",
        },
        ctx,
        { getCompany },
        { getCurrency },
      ),
    );

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

  it("returns error when currency not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const company = { id: "company-1" };
    mock.enqueueResults([company], []);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          name: "Acme Corp",
          type: "ORGANIZATION",
          companyId: "company-1",
          preferredCurrencyId: "nonexistent",
        },
        ctx,
        { getCompany },
        { getCurrency },
      ),
    );

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