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 {
  InsufficientAvailableStockError,
  InvalidReservationQuantitiesError,
  StockReservationNotFoundError,
  StockReservationNotOpenError,
  StorageLocationNotFoundError,
} from "../lib/errors.generated";
import { mockItemManagementQueries, mockOrganizationQueries } from "../testing/commandTestUtils";
import {
  baseActiveItem,
  baseActiveSite,
  baseStockLevel,
  baseStockReservation,
} from "../testing/fixtures";
import { run, type UpdateStockReservationInput } from "./updateStockReservation";

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

  const input: UpdateStockReservationInput = {
    id: "stock-reservation-1",
    reservedQuantity: "20",
  };

  it("updates reserved quantity successfully", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedReservation = { ...baseStockReservation, reservedQuantity: "20", status: "OPEN" };
    mock.enqueueResults(
      [baseStockReservation],
      [{ id: "location-1" }],
      [baseStockLevel],
      [baseStockReservation],
      [updatedReservation],
    );

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockReservation.reservedQuantity).toBe("20");
    }
    expect(mock.updates.length).toBeGreaterThan(0);
  });

  it("partially updates required date without rewriting omitted fields", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const requiredDate = new Date("2024-02-01T00:00:00.000Z");
    const updatedReservation = { ...baseStockReservation, requiredDate, status: "OPEN" };
    mock.enqueueResults(
      [baseStockReservation],
      [{ id: "location-1" }],
      [baseStockLevel],
      [baseStockReservation],
      [updatedReservation],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: "stock-reservation-1", requiredDate },
        ctx,
        mockItemManagementQueries(baseActiveItem),
        mockOrganizationQueries(baseActiveSite),
      ),
    );
    const updateSet = mock.updates[0].updateValues();

    expect(result.ok).toBe(true);
    expect(updateSet.requiredDate).toBe(requiredDate);
    expect(updateSet).not.toHaveProperty("reservedQuantity");
  });

  it("updates source document id for a reservation slice", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedReservation = {
      ...baseStockReservation,
      sourceId: "sales-order-2",
      status: "OPEN",
    };
    mock.enqueueResults(
      [baseStockReservation],
      [{ id: "location-1" }],
      [baseStockLevel],
      [baseStockReservation],
      [updatedReservation],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        {
          id: "stock-reservation-1",
          sourceId: "sales-order-2",
        },
        ctx,
        mockItemManagementQueries(baseActiveItem),
        mockOrganizationQueries(baseActiveSite),
      ),
    );
    const updateSet = mock.updates[0].updateValues();

    expect(result.ok).toBe(true);
    expect(updateSet.sourceId).toBe("sales-order-2");
    expect(updateSet).not.toHaveProperty("sourceType");
    expect(updateSet).not.toHaveProperty("sourceLineId");
  });

  it("returns error when changing site would leave the existing location outside the site", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseStockReservation, storageLocationId: "location-1" }], []);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: "stock-reservation-1", siteId: "site-2" },
        ctx,
        mockItemManagementQueries(baseActiveItem),
        mockOrganizationQueries({ ...baseActiveSite, id: "site-2" }),
      ),
    );

    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(StorageLocationNotFoundError);
    }
    expect(mock.updates).toHaveLength(0);
  });

  it("allows changing site when clearing the location", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const updatedReservation = {
      ...baseStockReservation,
      siteId: "site-2",
      storageLocationId: null,
      status: "OPEN",
    };
    mock.enqueueResults(
      [{ ...baseStockReservation, storageLocationId: "location-1" }],
      [{ id: "location-2" }],
      [baseStockLevel],
      [baseStockReservation],
      [updatedReservation],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { id: "stock-reservation-1", siteId: "site-2", storageLocationId: null },
        ctx,
        mockItemManagementQueries(baseActiveItem),
        mockOrganizationQueries({ ...baseActiveSite, id: "site-2" }),
      ),
    );

    expect(result.ok).toBe(true);
    const updateSet = mock.updates[0].updateValues();
    expect(updateSet.siteId).toBe("site-2");
    expect(updateSet.storageLocationId).toBeNull();
  });

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

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

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

  it("returns error when reservation is not open", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseStockReservation, status: "CLOSED" }]);

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

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

  it("returns error when reserved quantity is less than consumed quantity", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([{ ...baseStockReservation, consumedQuantity: "8" }]);

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { ...input, reservedQuantity: "5" },
        ctx,
        mockItemManagementQueries(baseActiveItem),
        mockOrganizationQueries(baseActiveSite),
      ),
    );

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

  it("returns error when updated open quantity exceeds available stock", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults(
      [baseStockReservation],
      [{ id: "location-1" }],
      [baseStockLevel],
      [{ ...baseStockReservation, id: "other", reservedQuantity: "80" }],
    );

    const result = await mock.withTx((trx) =>
      run(
        trx,
        { ...input, reservedQuantity: "20" },
        ctx,
        mockItemManagementQueries(baseActiveItem),
        mockOrganizationQueries(baseActiveSite),
      ),
    );

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