import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { StatusFilterRequiredError, CompanyScopeRequiredError } from "../lib/errors.generated";
import { expectOk, expectErr } from "../testing/commandTestUtils";
import { baseReleasedProductionOrder, baseInProgressProductionOrder } from "../testing/fixtures";
import { run } from "./listProductionOrdersByStatus";

describe("listProductionOrdersByStatus", () => {
  it("lists released production orders for a company", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseReleasedProductionOrder],
      [{ productionOrderId: "production-order-2", status: "COLLECTING" }],
    );

    const result = await run(mock.db, {
      companyId: "company-1",
      status: "RELEASED",
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);

    expect(mock.selects).toHaveLength(2);
    expect(mock.selects[0].sql).toMatch(/"companyId"/);
    expect(mock.selects[0].sql).toMatch(/"status"/);
    expect(mock.selects[0].parameters).toContain("company-1");
    expect(mock.selects[0].parameters).toContain("RELEASED");
    expect(mock.selects[0].sql).toMatch(/order by .*"plannedStartDate" asc/i);
  });

  it("lists in-progress production orders for a site", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseInProgressProductionOrder], []);

    const result = await run(mock.db, {
      companyId: "company-1",
      status: "IN_PROGRESS",
      siteId: "site-1",
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);

    expect(mock.selects[0].sql).toMatch(/"siteId"/);
    expect(mock.selects[0].parameters).toContain("site-1");
    expect(mock.selects[0].parameters).toContain("IN_PROGRESS");
  });

  it("filters production orders by produced item when provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseReleasedProductionOrder], []);

    const result = await run(mock.db, {
      companyId: "company-1",
      status: "RELEASED",
      orderedItemId: "item-1",
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);
    expect(items[0]).toMatchObject({ orderedItemId: "item-1" });

    expect(mock.selects[0].sql).toMatch(/"orderedItemId"/);
    expect(mock.selects[0].parameters).toContain("item-1");
  });

  it("filters production orders by planned date range when provided", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseReleasedProductionOrder], []);

    const result = await run(mock.db, {
      companyId: "company-1",
      status: "RELEASED",
      plannedStartDateFrom: new Date("2024-01-01T00:00:00.000Z"),
      plannedStartDateTo: new Date("2024-12-31T23:59:59.000Z"),
    });
    const { items } = expectOk<{ items: unknown[]; hasNextPage: boolean }>(result as never);

    expect(items).toHaveLength(1);

    expect(mock.selects[0].sql).toMatch(/"plannedStartDate"/);
    expect(mock.selects[0].parameters).toContainEqual(new Date("2024-01-01T00:00:00.000Z"));
    expect(mock.selects[0].parameters).toContainEqual(new Date("2024-12-31T23:59:59.000Z"));
  });

  it("returns summary fields with site and cost-summary status", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseReleasedProductionOrder],
      [{ productionOrderId: "production-order-2", status: "COLLECTING" }],
    );

    const result = await run(mock.db, {
      companyId: "company-1",
      status: "RELEASED",
    });
    const { items } = expectOk<{
      items: {
        siteId: string;
        status: string;
        plannedQuantity: number;
        plannedStartDate: Date;
        costSummaryStatus: string | null;
      }[];
      hasNextPage: boolean;
    }>(result as never);

    expect(items[0].siteId).toBe("site-1");
    expect(items[0].status).toBe("RELEASED");
    expect(items[0].plannedQuantity).toBe(100);
    expect(items[0].plannedStartDate).toEqual(new Date("2024-03-01T00:00:00.000Z"));
    expect(items[0].costSummaryStatus).toBe("COLLECTING");
  });

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

    const result = await run(mock.db, {
      companyId: "company-1",
      status: [],
    });
    expectErr(result as never, StatusFilterRequiredError);
  });

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

    const result = await run(mock.db, {
      companyId: "",
      status: "RELEASED",
    });
    expectErr(result as never, CompanyScopeRequiredError);
  });
});
