import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import { CompanyNotFoundError, IdentifierRequiredError } from "../lib/errors.generated";
import { baseCompany, basePriceList } from "../testing/fixtures";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import { run } from "./createSalesPriceList";

describe("createSalesPriceList", () => {
  it("creates a draft price list for a valid company", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const created = { ...basePriceList, id: "price-list-9", status: "DRAFT" as const };
    spies.select.mockReturnValueOnce(baseCompany);
    spies.insert.mockReturnValueOnce(created);

    const result = await run(
      db,
      { companyId: baseCompany.id, name: "Promo Prices", code: "PROMO" },
      commandCtx,
    );

    const value = expectOk(result);
    expect(value.salesPriceList).toEqual(created);
  });

  it("throws when required SalesPriceList fields are missing", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCompany);

    const result = await run(db, { companyId: baseCompany.id, name: "" }, commandCtx);

    expectErr(result, IdentifierRequiredError);
  });

  it("creates the SalesPriceList in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseCompany);
    spies.insert.mockReturnValueOnce({ ...basePriceList, status: "DRAFT" as const });

    const result = await run(
      db,
      { companyId: baseCompany.id, name: basePriceList.name, priority: basePriceList.priority },
      commandCtx,
    );

    expectOk(result);
    expect(spies.values).toHaveBeenCalledWith(
      expect.objectContaining({
        companyId: baseCompany.id,
        status: "DRAFT",
      }),
    );
  });

  it("throws when the company does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(
      db,
      { companyId: baseCompany.id, name: basePriceList.name },
      commandCtx,
    );

    expectErr(result, CompanyNotFoundError);
  });
});
