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

describe("activateSalesPriceList", () => {
  it("activates a draft SalesPriceList", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const activated = {
      ...draftPriceList,
      status: "ACTIVE" as const,
      updatedAt: new Date("2024-01-02T00:00:00.000Z"),
    };
    spies.select.mockReturnValueOnce(draftPriceList).mockReturnValueOnce(baseCompany);
    spies.update.mockReturnValueOnce(activated);

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

    expectOk(result);
  });

  it("throws when SalesPriceList is not in DRAFT status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(basePriceList);

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

    expectErr(result, InvalidSalespricelistStatusError);
  });

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

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

    expectErr(result, SalespricelistNotFoundError);
  });

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

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

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