import type { CommandContext } from "@tailor-platform/erp-kit/core";
import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } 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 { db, spies } = createMockDb<Transaction>();
    const updatedReservation = { ...baseStockReservation, reservedQuantity: "20", status: "OPEN" };
    spies.select
      .mockReturnValueOnce(baseStockReservation)
      .mockReturnValueOnce([{ id: "location-1" }])
      .mockReturnValueOnce([baseStockLevel])
      .mockReturnValueOnce([baseStockReservation]);
    spies.update.mockReturnValueOnce(updatedReservation);

    const result = await run(
      db,
      input,
      ctx,
      mockItemManagementQueries(baseActiveItem),
      mockOrganizationQueries(baseActiveSite),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockReservation.reservedQuantity).toBe("20");
    }
    expect(spies.update).toHaveBeenCalled();
  });

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

    const result = await run(
      db,
      { id: "stock-reservation-1", requiredDate },
      ctx,
      mockItemManagementQueries(baseActiveItem),
      mockOrganizationQueries(baseActiveSite),
    );
    const updateSet = spies.set.mock.calls[0][0] as Record<string, unknown>;

    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 { db, spies } = createMockDb<Transaction>();
    const updatedReservation = {
      ...baseStockReservation,
      sourceId: "sales-order-2",
      status: "OPEN",
    };
    spies.select
      .mockReturnValueOnce(baseStockReservation)
      .mockReturnValueOnce([{ id: "location-1" }])
      .mockReturnValueOnce([baseStockLevel])
      .mockReturnValueOnce([baseStockReservation]);
    spies.update.mockReturnValueOnce(updatedReservation);

    const result = await run(
      db,
      {
        id: "stock-reservation-1",
        sourceId: "sales-order-2",
      },
      ctx,
      mockItemManagementQueries(baseActiveItem),
      mockOrganizationQueries(baseActiveSite),
    );
    const updateSet = spies.set.mock.calls[0][0] as Record<string, unknown>;

    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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce({ ...baseStockReservation, storageLocationId: "location-1" })
      .mockReturnValueOnce(undefined);

    const result = await run(
      db,
      { 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(spies.update).not.toHaveBeenCalled();
  });

  it("allows changing site when clearing the location", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedReservation = {
      ...baseStockReservation,
      siteId: "site-2",
      storageLocationId: null,
      status: "OPEN",
    };
    spies.select
      .mockReturnValueOnce({ ...baseStockReservation, storageLocationId: "location-1" })
      .mockReturnValueOnce([{ id: "location-2" }])
      .mockReturnValueOnce([baseStockLevel])
      .mockReturnValueOnce([baseStockReservation]);
    spies.update.mockReturnValueOnce(updatedReservation);

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

    expect(result.ok).toBe(true);
    const updateSet = spies.set.mock.calls[0][0] as Record<string, unknown>;
    expect(updateSet.siteId).toBe("site-2");
    expect(updateSet.storageLocationId).toBeNull();
  });

  it("returns error when reservation not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);

    const result = await run(
      db,
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseStockReservation, status: "CLOSED" });

    const result = await run(
      db,
      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 { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseStockReservation, consumedQuantity: "8" });

    const result = await run(
      db,
      { ...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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseStockReservation)
      .mockReturnValueOnce([{ id: "location-1" }])
      .mockReturnValueOnce([baseStockLevel])
      .mockReturnValueOnce([{ ...baseStockReservation, id: "other", reservedQuantity: "80" }]);

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

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