import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  DescriptionRequiredError,
  EmptyPurchaseRequisitionLinesError,
  InvalidEstimatedUnitPriceError,
  InvalidQuantityError,
  ItemNotFoundError,
  PartnerNotSupplierError,
  SupplierNotActiveError,
  SupplierNotFoundError,
} from "../lib/errors.generated";
import { commandCtx, expectErr, expectOk } from "../testing/commandTestUtils";
import {
  baseCompany,
  baseItem,
  basePurchaseRequisition,
  basePurchaseRequisitionLines,
  baseSupplier,
  baseSupplierRole,
  baseUnit,
  inactiveSupplier,
} from "../testing/fixtures";
import { mockBPQueries, mockItemQueries } from "../testing/moduleMocks";
import { run } from "./createPurchaseRequisition";

describe("createPurchaseRequisition", () => {
  it("creates a draft purchase requisition with valid requester and lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePurchaseRequisition]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, requesterId: "requester-1" },
          lines: basePurchaseRequisitionLines,
        },
        commandCtx,
        mockBPQueries(),
        mockItemQueries({ item: baseItem }),
      ),
    );

    expect(expectOk(result).purchaseRequisition.status).toBe("DRAFT");
  });

  it("creates a requisition with lines referencing an item", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([basePurchaseRequisition]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, requesterId: "requester-1" },
          lines: [
            {
              description: "Custom item description",
              quantity: "5",
              estimatedUnitPrice: "10",
              itemId: baseItem.id,
              unitId: baseUnit.id,
            },
          ],
        },
        commandCtx,
        mockBPQueries(),
        mockItemQueries({ item: baseItem }),
      ),
    );

    expect(expectOk(result).purchaseRequisition.status).toBe("DRAFT");
  });

  it("creates a requisition with optional suggested supplier on lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const bpQ = mockBPQueries({ partner: baseSupplier, partnerRole: baseSupplierRole });
    mock.enqueueResults([basePurchaseRequisition]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, requesterId: "requester-1" },
          lines: [
            {
              ...basePurchaseRequisitionLines[0],
              suggestedSupplierId: baseSupplier.id,
            },
          ],
        },
        commandCtx,
        bpQ,
        mockItemQueries({ item: baseItem }),
      ),
    );

    expect(expectOk(result).purchaseRequisition.status).toBe("DRAFT");
  });

  it("returns error when no lines are provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, requesterId: "requester-1" },
          lines: [],
        },
        commandCtx,
        mockBPQueries(),
        mockItemQueries({ item: baseItem }),
      ),
    );

    expectErr(result, EmptyPurchaseRequisitionLinesError);
  });

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, requesterId: "requester-1" },
          lines: [{ ...basePurchaseRequisitionLines[0], description: "" }],
        },
        commandCtx,
        mockBPQueries(),
        mockItemQueries({ item: baseItem }),
      ),
    );

    expectErr(result, DescriptionRequiredError);
  });

  it("returns DescriptionRequiredError with empty string when description is undefined-like", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, requesterId: "requester-1" },
          lines: [
            {
              ...basePurchaseRequisitionLines[0],
              description: undefined as unknown as string,
            },
          ],
        },
        commandCtx,
        mockBPQueries(),
        mockItemQueries({ item: baseItem }),
      ),
    );

    expectErr(result, DescriptionRequiredError);
  });

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, requesterId: "requester-1" },
          lines: [{ ...basePurchaseRequisitionLines[0], quantity: "0" }],
        },
        commandCtx,
        mockBPQueries(),
        mockItemQueries({ item: baseItem }),
      ),
    );

    expectErr(result, InvalidQuantityError);
  });

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

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, requesterId: "requester-1" },
          lines: [{ ...basePurchaseRequisitionLines[0], estimatedUnitPrice: "-1" }],
        },
        commandCtx,
        mockBPQueries(),
        mockItemQueries({ item: baseItem }),
      ),
    );

    expectErr(result, InvalidEstimatedUnitPriceError);
  });

  it("returns error when a referenced item does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, requesterId: "requester-1" },
          lines: [{ ...basePurchaseRequisitionLines[0], itemId: "missing-item" }],
        },
        commandCtx,
        mockBPQueries(),
        mockItemQueries(),
      ),
    );

    expectErr(result, ItemNotFoundError);
  });

  it("returns error when a suggested supplier does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const bpQ = mockBPQueries();

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, requesterId: "requester-1" },
          lines: [
            {
              ...basePurchaseRequisitionLines[0],
              suggestedSupplierId: "missing-supplier",
            },
          ],
        },
        commandCtx,
        bpQ,
        mockItemQueries({ item: baseItem }),
      ),
    );

    expectErr(result, SupplierNotFoundError);
  });

  it("returns error when a suggested supplier is inactive", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const bpQ = mockBPQueries({ partner: inactiveSupplier });

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, requesterId: "requester-1" },
          lines: [
            {
              ...basePurchaseRequisitionLines[0],
              suggestedSupplierId: inactiveSupplier.id,
            },
          ],
        },
        commandCtx,
        bpQ,
        mockItemQueries({ item: baseItem }),
      ),
    );

    expectErr(result, SupplierNotActiveError);
  });

  it("returns error when a suggested supplier is not classified as a supplier", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const bpQ = mockBPQueries({ partner: baseSupplier });

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          header: { companyId: baseCompany.id, requesterId: "requester-1" },
          lines: [
            {
              ...basePurchaseRequisitionLines[0],
              suggestedSupplierId: baseSupplier.id,
            },
          ],
        },
        commandCtx,
        bpQ,
        mockItemQueries({ item: baseItem }),
      ),
    );

    expectErr(result, PartnerNotSupplierError);
  });
});
