import { ok } from "@tailor-platform/erp-kit/core";
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 {
  StockAdjustmentNotFoundError,
  InvalidStatusError,
  EmptyAdjustmentLinesError,
  InvalidQuantityError,
  ItemNotFoundError,
  ItemNotActiveError,
  StorageLocationNotFoundError,
  StorageLocationNotActiveError,
  InvalidFromStockCategoryError,
  LotNotFoundError,
  SerialNotFoundError,
} from "../lib/errors.generated";
import {
  baseDraftAdjustment,
  baseSubmittedAdjustment,
  baseRejectedAdjustment,
  baseConfirmedAdjustment,
  correctionIncreaseLine,
  baseStorageLocation,
  baseInactiveLocation,
} from "../testing/fixtures";
import { run } from "./updateStockAdjustment";

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

  const mockGetItemFound = {
    getItem: () => Promise.resolve(ok({ item: { id: "item-1", status: "ACTIVE" } })),
  };

  const mockGetItemNotFound = {
    getItem: () => Promise.resolve(ok({ item: null })),
  };

  const mockGetItemInactive = {
    getItem: () => Promise.resolve(ok({ item: { id: "item-1", status: "INACTIVE" } })),
  };

  const validLine = {
    itemId: "item-1",
    storageLocationId: "location-1",
    quantity: "10",
    adjustmentDirection: "INCREASE" as const,
  };

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

    const result = await run(db, { id: "nonexistent" }, ctx, mockGetItemFound);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(StockAdjustmentNotFoundError);
    }
  });

  it("returns error when stock adjustment is not in DRAFT or REJECTED status", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseSubmittedAdjustment);

    const result = await run(db, { id: "adjustment-2" }, ctx, mockGetItemFound);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStatusError);
    }
  });

  it("returns error when status is CONFIRMED", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseConfirmedAdjustment);

    const result = await run(db, { id: "adjustment-4" }, ctx, mockGetItemFound);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidStatusError);
    }
  });

  it("returns error when update would leave zero lines", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftAdjustment);

    const result = await run(db, { id: "adjustment-1", lines: [] }, ctx, mockGetItemFound);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(EmptyAdjustmentLinesError);
    }
  });

  it("returns error when item does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftAdjustment);

    const result = await run(
      db,
      { id: "adjustment-1", lines: [validLine] },
      ctx,
      mockGetItemNotFound,
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ItemNotFoundError);
    }
  });

  it("returns error when line quantity is zero or negative", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftAdjustment);

    const result = await run(
      db,
      { id: "adjustment-1", lines: [{ ...validLine, quantity: "0" }] },
      ctx,
      mockGetItemFound,
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidQuantityError);
    }
  });

  it("returns error when storage location does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftAdjustment); // fetch adjustment
    spies.select.mockReturnValueOnce(undefined); // location not found

    const result = await run(db, { id: "adjustment-1", lines: [validLine] }, ctx, mockGetItemFound);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(StorageLocationNotFoundError);
    }
  });

  it("returns error when item is not active", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftAdjustment);

    const result = await run(
      db,
      { id: "adjustment-1", lines: [validLine] },
      ctx,
      mockGetItemInactive,
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ItemNotActiveError);
    }
  });

  it("returns error when storage location is not active", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftAdjustment); // fetch adjustment
    spies.select.mockReturnValueOnce(baseInactiveLocation); // location found but INACTIVE

    const result = await run(db, { id: "adjustment-1", lines: [validLine] }, ctx, mockGetItemFound);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(StorageLocationNotActiveError);
    }
  });

  it("rejects fromStockCategory set on non-SCRAP lines", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(baseDraftAdjustment); // fetch adjustment (adjustmentType=CORRECTION)
    spies.select.mockReturnValueOnce(baseStorageLocation); // location found

    const result = await run(
      db,
      {
        id: "adjustment-1",
        lines: [{ ...validLine, fromStockCategory: "AVAILABLE" as const }],
      },
      ctx,
      mockGetItemFound,
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidFromStockCategoryError);
    }
  });

  it("returns error when lot does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseDraftAdjustment) // fetch adjustment
      .mockReturnValueOnce(baseStorageLocation) // location found
      .mockReturnValueOnce(undefined); // lot not found

    const result = await run(
      db,
      {
        id: "adjustment-1",
        lines: [{ ...validLine, lotId: "nonexistent-lot" }],
      },
      ctx,
      mockGetItemFound,
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(LotNotFoundError);
    }
  });

  it("returns error when serial number does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseDraftAdjustment) // fetch adjustment
      .mockReturnValueOnce(baseStorageLocation) // location found
      .mockReturnValueOnce(undefined); // serial not found

    const result = await run(
      db,
      {
        id: "adjustment-1",
        lines: [{ ...validLine, serialNumberId: "nonexistent-serial" }],
      },
      ctx,
      mockGetItemFound,
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(SerialNotFoundError);
    }
  });

  it("updates reason code on a DRAFT adjustment", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedAdjustment = { ...baseDraftAdjustment, reasonCode: "updated-reason" };
    const existingLines = [correctionIncreaseLine];

    spies.select
      .mockReturnValueOnce(baseDraftAdjustment) // fetch adjustment
      .mockReturnValueOnce(existingLines); // fetch existing lines
    spies.update.mockReturnValue(updatedAdjustment);

    const result = await run(
      db,
      { id: "adjustment-1", reasonCode: "updated-reason" },
      ctx,
      mockGetItemFound,
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockAdjustment.reasonCode).toBe("updated-reason");
    }
  });

  it("replaces lines when provided", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedAdjustment = { ...baseDraftAdjustment };
    const newLine = { ...correctionIncreaseLine, quantity: 10 };

    spies.select.mockReturnValueOnce(baseDraftAdjustment); // fetch adjustment
    // location found for line validation
    spies.select.mockReturnValueOnce(baseStorageLocation);
    spies.update.mockReturnValue(updatedAdjustment);
    spies.delete.mockReturnValue(undefined); // delete existing lines
    spies.insert.mockReturnValue([newLine]); // bulk insert new lines

    const result = await run(db, { id: "adjustment-1", lines: [validLine] }, ctx, mockGetItemFound);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockAdjustmentLines).toHaveLength(1);
    }
    expect(spies.delete).toHaveBeenCalled();
    expect(spies.insert).toHaveBeenCalled();
  });

  it("transitions REJECTED adjustment back to DRAFT", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updatedAdjustment = {
      ...baseRejectedAdjustment,
      status: "DRAFT",
      rejectionReason: null,
    };
    const existingLines = [correctionIncreaseLine];

    spies.select
      .mockReturnValueOnce(baseRejectedAdjustment) // fetch adjustment
      .mockReturnValueOnce(existingLines); // fetch existing lines
    spies.update.mockReturnValue(updatedAdjustment);

    const result = await run(
      db,
      { id: "adjustment-3", reasonCode: "revised-reason" },
      ctx,
      mockGetItemFound,
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.stockAdjustment.status).toBe("DRAFT");
      expect(result.value.stockAdjustment.rejectionReason).toBeNull();
    }
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({ status: "DRAFT", rejectionReason: null }),
    );
  });
});
