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

describe("updateSalesPriceList", () => {
  it("updates mutable SalesPriceList fields", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = {
      ...draftPriceList,
      name: "Updated List",
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    spies.select.mockReturnValueOnce(draftPriceList).mockReturnValueOnce(baseCompany);
    spies.update.mockReturnValueOnce(updated);

    const result = await run(
      db,
      { salesPriceListId: draftPriceList.id, name: "Updated List", priority: 20 },
      commandCtx,
    );

    expectOk(result);
  });

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

    const result = await run(
      db,
      { salesPriceListId: draftPriceList.id, name: "Updated List" },
      commandCtx,
    );

    expectErr(result, SalespricelistNotFoundError);
  });

  it("returns error when SalesPriceList is not editable", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...basePriceList, status: "INACTIVE" });

    const result = await run(
      db,
      { salesPriceListId: basePriceList.id, name: "Updated List" },
      commandCtx,
    );

    expectErr(result, SalespricelistNotEditableError);
  });

  it("returns error when the company backing the price list does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(draftPriceList).mockReturnValueOnce(undefined);

    const result = await run(
      db,
      { salesPriceListId: draftPriceList.id, name: "Updated List" },
      commandCtx,
    );

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