import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { InventorySupplyPlanNotFoundError, SupplyPlanNotOpenError } from "../lib/errors.generated";
import { baseSupplyPlan } from "../testing/fixtures";
import { run } from "./closeInventorySupplyPlan";

describe("closeInventorySupplyPlan", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["inventory:supplyPlan:closeInventorySupplyPlan"],
  };

  const input = {
    target: "SUPPLY_PLAN" as const,
    id: "supply-plan-1",
  };

  it("closes supply plan by id", async () => {
    const closed = { ...baseSupplyPlan, status: "CLOSED" };
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseSupplyPlan], [closed]);

    const result = await mock.withTx((trx) => run(trx, input, ctx));

    expect(result.ok).toBe(true);
    if (!result.ok) {
      throw result.error;
    }
    expect(result.value).toHaveProperty("supplyPlan");
    if ("supplyPlan" in result.value) {
      expect(result.value.supplyPlan.status).toBe("CLOSED");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("returns error when supply plan not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) => run(trx, input, ctx));

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InventorySupplyPlanNotFoundError);
    }
  });

  it("returns error when supply plan is closed", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseSupplyPlan, status: "CLOSED" }]);

    const result = await mock.withTx((trx) => run(trx, input, ctx));

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(SupplyPlanNotOpenError);
    }
  });

  it("closes open supply plans for a source document", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseSupplyPlan, status: "CLOSED" }]);

    const result = await mock.withTx((trx) =>
      run(trx, { target: "SOURCE_DOCUMENT", sourceType: "PURCHASE_ORDER", sourceId: "po-1" }, ctx),
    );
    expect(result.ok).toBe(true);
    if (!result.ok) {
      throw result.error;
    }
    expect(result.value).toHaveProperty("supplyPlans");
    if ("supplyPlans" in result.value) {
      expect(result.value.supplyPlans).toHaveLength(1);
      expect(result.value.supplyPlans[0]?.status).toBe("CLOSED");
    }
    const update = mock.updates[0];
    expect(update.sql).toMatch(/"sourceType"/);
    expect(update.parameters).toContain("PURCHASE_ORDER");
    expect(update.sql).toMatch(/"sourceId"/);
    expect(update.parameters).toContain("po-1");
    expect(update.sql).toMatch(/"status"/);
    expect(update.parameters).toContain("OPEN");
  });

  it("closes open supply plans for selected source lines", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseSupplyPlan, status: "CLOSED" }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          target: "SOURCE_LINES",
          sourceType: "PURCHASE_ORDER",
          sourceLineIds: ["po-line-1"],
        },
        ctx,
      ),
    );

    expect(result.ok).toBe(true);
    if (!result.ok) {
      throw result.error;
    }
    expect(result.value).toHaveProperty("supplyPlans");
    const update = mock.updates[0];
    expect(update.sql).toMatch(/"sourceLineId" in/);
    expect(update.parameters).toContain("po-line-1");
  });

  it("returns no rows when sourceLineIds is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) =>
      run(trx, { target: "SOURCE_LINES", sourceType: "PURCHASE_ORDER", sourceLineIds: [] }, ctx),
    );
    expect(result.ok).toBe(true);
    if (!result.ok) {
      throw result.error;
    }
    expect(result.value).toHaveProperty("supplyPlans");
    if ("supplyPlans" in result.value) {
      expect(result.value.supplyPlans).toEqual([]);
    }
  });
});
