import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { GetUnitInput } from "../../primitives/query/getUnit";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  InvalidUomError,
  MissingRequiredFieldError,
  NoFieldsToUpdateError,
  ProductNotFoundError,
  UomLockedError,
} from "../lib/errors.generated";
import { baseActiveProduct, baseDraftProduct } from "../testing/fixtures";
import { run } from "./updateProduct";
import type { CommandContext } from "@tailor-platform/erp-kit/module";

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

  const baseUnit = {
    id: "unit-pcs",
    symbol: "pcs",
    name: "Pieces",
    roundingPrecision: 0,
    isActive: true,
    createdAt: new Date("2024-01-01"),
    updatedAt: null,
    categoryId: "uom-cat-1",
    conversionFactor: 1,
  };

  const mockGetUnit = (_db: unknown, input: GetUnitInput) =>
    Promise.resolve({
      ok: true as const,
      value: {
        unit: "id" in input && input.id === "unit-pcs" ? baseUnit : null,
      },
    });
  const primitivesQueries = { getUnit: mockGetUnit };

  it("returns error when product not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined);
    const result = await run(db, { id: "nonexistent", name: "New Name" }, ctx, primitivesQueries);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ProductNotFoundError);
    }
  });

  it("returns error when no fields provided", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseDraftProduct });
    const result = await run(db, { id: "product-1" }, ctx, primitivesQueries);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(NoFieldsToUpdateError);
    }
  });

  it("returns error when name is empty", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseDraftProduct });
    const result = await run(db, { id: "product-1", name: "" }, ctx, primitivesQueries);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(MissingRequiredFieldError);
    }
  });

  it("returns error when UoM locked on non-DRAFT", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseActiveProduct });
    const result = await run(db, { id: "product-2", unitId: "unit-pcs" }, ctx, primitivesQueries);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(UomLockedError);
    }
  });

  it("returns error when UoM is invalid", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce({ ...baseDraftProduct });
    const result = await run(
      db,
      { id: "product-1", unitId: "unit-invalid" },
      ctx,
      primitivesQueries,
    );
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidUomError);
    }
  });

  it("updates description successfully", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftProduct, description: "A new description" };
    spies.select.mockReturnValueOnce({ ...baseDraftProduct });
    spies.update.mockReturnValueOnce(updated);
    const result = await run(
      db,
      { id: "product-1", description: "A new description" },
      ctx,
      primitivesQueries,
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.product.description).toBe("A new description");
    }
  });

  it("updates UoM successfully on DRAFT product", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftProduct, unitId: "unit-pcs" };
    spies.select.mockReturnValueOnce({ ...baseDraftProduct });
    spies.update.mockReturnValueOnce(updated);
    const result = await run(db, { id: "product-1", unitId: "unit-pcs" }, ctx, primitivesQueries);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.product.unitId).toBe("unit-pcs");
    }
  });

  it("updates name successfully", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftProduct, name: "Updated Name" };
    spies.select.mockReturnValueOnce({ ...baseDraftProduct });
    spies.update.mockReturnValueOnce(updated);
    const result = await run(db, { id: "product-1", name: "Updated Name" }, ctx, primitivesQueries);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.product.name).toBe("Updated Name");
    }
  });

  it("looks up product by code and updates name", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftProduct, name: "Updated Name" };
    spies.select.mockReturnValueOnce({ ...baseDraftProduct });
    spies.update.mockReturnValueOnce(updated);
    const result = await run(
      db,
      { code: baseDraftProduct.code, name: "Updated Name" },
      ctx,
      primitivesQueries,
    );
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.product.name).toBe("Updated Name");
    }
  });

  it("passes custom fields through", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const updated = { ...baseDraftProduct, customField1: "value1" };
    spies.select.mockReturnValueOnce({ ...baseDraftProduct });
    spies.update.mockReturnValueOnce(updated);
    const result = await run(
      db,
      { id: "product-1", name: "Updated", customField1: "value1" },
      ctx,
      primitivesQueries,
    );
    expect(result.ok).toBe(true);
    expect(spies.set).toHaveBeenCalledWith(
      expect.objectContaining({
        customField1: "value1",
      }),
    );
  });
});
