import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import type { Transaction } from "../generated/kysely-tailordb";
import {
  baseActiveProduct,
  baseDraftProduct,
  baseColorAttribute,
  baseSizeAttribute,
  baseAttributeAssignment,
} from "../testing/fixtures";
import {
  ProductNotFoundError,
  InvalidProductStatusError,
  NoVariantAxesError,
  AttributeNotFoundError,
  AttributeValueNotFoundError,
  ItemCreationFailedError,
} from "../lib/errors.generated";
import { UnitNotFoundError } from "../../item-management/lib/errors.generated";
import type { GenerateVariantsInput } from "./generateVariants";
import { run } from "./generateVariants";
import { err, type CommandContext } from "@tailor-platform/erp-kit/module";

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

  const mockCreateItem = (_db: unknown, input: { sku: string; name: string; unitId: string }) =>
    Promise.resolve({
      ok: true as const,
      value: {
        item: {
          id: `item-${input.sku}`,
          sku: input.sku,
          name: input.name,
          barcode: null,
          unitId: input.unitId,
          status: "ACTIVE" as const,
          createdAt: new Date(),
          updatedAt: null,
        },
      },
    });
  const skuStrategy = (code: string, _values: string[], count: number) =>
    `${code}-${String(count + 1).padStart(3, "0")}`;
  const deps = {
    itemManagement: { createItem: mockCreateItem },
    skuStrategy,
  };

  it("should return ProductNotFoundError when product does not exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // getProduct -> null
    spies.select.mockReturnValueOnce(undefined);
    const input: GenerateVariantsInput = { productId: "non-existent" };
    const result = await run(db, input, ctx, deps);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ProductNotFoundError);
    }
  });

  it("should return InvalidProductStatusError when product is not ACTIVE", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // getProduct -> draft product (not ACTIVE)
    spies.select.mockReturnValueOnce(baseDraftProduct);
    const input: GenerateVariantsInput = { productId: baseDraftProduct.id };
    const result = await run(db, input, ctx, deps);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(InvalidProductStatusError);
    }
  });

  it("should return NoVariantAxesError when no attribute assignments exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // 1. getProduct -> active product
    spies.select.mockReturnValueOnce(baseActiveProduct);
    // 2. listProductAttributeAssignments -> empty
    spies.select.mockReturnValueOnce([]);

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await run(db, input, ctx, deps);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(NoVariantAxesError);
    }
  });

  it("should return AttributeNotFoundError when referenced attribute no longer exists", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // 1. getProduct -> active product
    spies.select.mockReturnValueOnce(baseActiveProduct);
    // 2. listProductAttributeAssignments -> assignment referencing an attribute
    const colorRedAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-1",
    };
    spies.select.mockReturnValueOnce([colorRedAssignment]);
    // 3. data integrity: select ProductAttribute by ID -> deleted between queries
    spies.select.mockReturnValueOnce(undefined);

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await run(db, input, ctx, deps);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(AttributeNotFoundError);
    }
  });

  it("should return AttributeValueNotFoundError when referenced value no longer exists", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // 1. getProduct -> active product
    spies.select.mockReturnValueOnce(baseActiveProduct);
    // 2. listProductAttributeAssignments -> assignment with a value ID
    const colorRedAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-1",
    };
    spies.select.mockReturnValueOnce([colorRedAssignment]);
    // 3. data integrity: attribute exists
    spies.select.mockReturnValueOnce(baseColorAttribute);
    // 4. data integrity: value deleted between queries
    spies.select.mockReturnValueOnce(undefined);

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await run(db, input, ctx, deps);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(AttributeValueNotFoundError);
    }
  });

  it("should skip existing variant combinations (idempotency)", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // 1. getProduct -> active product
    spies.select.mockReturnValueOnce(baseActiveProduct);
    // 2. listProductAttributeAssignments -> one assignment
    const colorRedAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-1",
    };
    spies.select.mockReturnValueOnce([colorRedAssignment]);
    // 3. data integrity: attribute exists
    spies.select.mockReturnValueOnce(baseColorAttribute);
    // 4. data integrity: value exists
    spies.select.mockReturnValueOnce({ id: "value-1" });
    // 5. listProductVariants -> existing variant with same key
    const existingVariant = {
      id: "variant-existing",
      productId: baseActiveProduct.id,
      axisValueKey: "value-1",
      itemId: "item-existing",
      createdAt: new Date(),
      updatedAt: null,
    };
    spies.select.mockReturnValueOnce([existingVariant]);

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await run(db, input, ctx, deps);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.variants).toHaveLength(0);
    }
    // No inserts should have happened since all combinations already exist
    expect(spies.insert).not.toHaveBeenCalled();
  });

  it("should return ItemCreationFailedError when item creation fails", async () => {
    const { db, spies } = createMockDb<Transaction>();
    const failingCreateItem = () => Promise.resolve(err(new UnitNotFoundError("unit-pcs")));
    const failingDeps = {
      itemManagement: { createItem: failingCreateItem },
      skuStrategy,
    };

    // 1. getProduct -> active product
    spies.select.mockReturnValueOnce(baseActiveProduct);
    // 2. listProductAttributeAssignments -> one assignment
    const colorRedAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-1",
    };
    spies.select.mockReturnValueOnce([colorRedAssignment]);
    // 3. data integrity: attribute exists
    spies.select.mockReturnValueOnce(baseColorAttribute);
    // 4. data integrity: value exists
    spies.select.mockReturnValueOnce({ id: "value-1" });
    // 5. listProductVariants -> no existing variants
    spies.select.mockReturnValueOnce([]);

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await run(db, input, ctx, failingDeps);
    expect(result.ok).toBe(false);
    if (!result.ok) {
      expect(result.error).toBeInstanceOf(ItemCreationFailedError);
    }
  });

  it("should generate multi-axis cartesian product variants", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // 1. getProduct -> active product
    spies.select.mockReturnValueOnce(baseActiveProduct);
    // 2. listProductAttributeAssignments -> color and size assignments
    const colorRedAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-1",
    };
    const colorBlueAssignment = {
      ...baseAttributeAssignment,
      id: "assignment-2",
      valueId: "value-2",
    };
    const sizeSmallAssignment = {
      ...baseAttributeAssignment,
      id: "assignment-3",
      attributeId: baseSizeAttribute.id,
      valueId: "value-3",
    };
    spies.select.mockReturnValueOnce([
      colorRedAssignment,
      colorBlueAssignment,
      sizeSmallAssignment,
    ]);
    // 3. data integrity: attributes exist (color, size)
    spies.select.mockReturnValueOnce(baseColorAttribute);
    spies.select.mockReturnValueOnce(baseSizeAttribute);
    // 4. data integrity: values exist (value-1, value-2, value-3)
    spies.select.mockReturnValueOnce({ id: "value-1" });
    spies.select.mockReturnValueOnce({ id: "value-2" });
    spies.select.mockReturnValueOnce({ id: "value-3" });
    // 5. listProductVariants -> no existing variants
    spies.select.mockReturnValueOnce([]);
    // 6. For each combination (2 combos: [value-1,value-3], [value-2,value-3]):
    const variant1 = {
      id: "variant-new-1",
      productId: baseActiveProduct.id,
      axisValueKey: "value-1|value-3",
      itemId: `item-${baseActiveProduct.code}-001`,
      createdAt: new Date(),
      updatedAt: null,
    };
    const variant2 = {
      id: "variant-new-2",
      productId: baseActiveProduct.id,
      axisValueKey: "value-2|value-3",
      itemId: `item-${baseActiveProduct.code}-002`,
      createdAt: new Date(),
      updatedAt: null,
    };
    spies.insert.mockReturnValueOnce(variant1);
    spies.insert.mockReturnValueOnce(variant2);

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await run(db, input, ctx, deps);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.variants).toHaveLength(2);
    }
  });

  it("should only generate new combinations when some already exist", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // 1. getProduct -> active product
    spies.select.mockReturnValueOnce(baseActiveProduct);
    // 2. listProductAttributeAssignments -> two color assignments
    const colorRedAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-1",
    };
    const colorBlueAssignment = {
      ...baseAttributeAssignment,
      id: "assignment-2",
      valueId: "value-2",
    };
    spies.select.mockReturnValueOnce([colorRedAssignment, colorBlueAssignment]);
    // 3. data integrity: attribute exists
    spies.select.mockReturnValueOnce(baseColorAttribute);
    // 4. data integrity: values exist
    spies.select.mockReturnValueOnce({ id: "value-1" });
    spies.select.mockReturnValueOnce({ id: "value-2" });
    // 5. listProductVariants -> one existing variant for value-1
    const existingVariant = {
      id: "variant-existing",
      productId: baseActiveProduct.id,
      axisValueKey: "value-1",
      itemId: "item-existing",
      createdAt: new Date(),
      updatedAt: null,
    };
    spies.select.mockReturnValueOnce([existingVariant]);
    // 6. Only value-2 combination should be created
    const newVariant = {
      id: "variant-new-1",
      productId: baseActiveProduct.id,
      axisValueKey: "value-2",
      itemId: `item-${baseActiveProduct.code}-002`,
      createdAt: new Date(),
      updatedAt: null,
    };
    spies.insert.mockReturnValueOnce(newVariant);

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await run(db, input, ctx, deps);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.variants).toHaveLength(1);
      expect(result.value.variants[0]).toEqual(newVariant);
    }
  });

  it("should generate variants successfully", async () => {
    const { db, spies } = createMockDb<Transaction>();
    // 1. getProduct -> active product
    spies.select.mockReturnValueOnce(baseActiveProduct);
    // 2. listProductAttributeAssignments -> assignments for color
    const colorRedAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-1",
    };
    const colorBlueAssignment = {
      ...baseAttributeAssignment,
      id: "assignment-2",
      valueId: "value-2",
    };
    spies.select.mockReturnValueOnce([colorRedAssignment, colorBlueAssignment]);
    // 3. data integrity: attribute exists
    spies.select.mockReturnValueOnce(baseColorAttribute);
    // 4. data integrity: values exist
    spies.select.mockReturnValueOnce({ id: "value-1" });
    spies.select.mockReturnValueOnce({ id: "value-2" });
    // 5. listProductVariants -> no existing variants
    spies.select.mockReturnValueOnce([]);
    // 6. For each combination (2 combos: value-1, value-2):
    const variant1 = {
      id: "variant-new-1",
      productId: baseActiveProduct.id,
      axisValueKey: "value-1",
      itemId: `item-${baseActiveProduct.code}-001`,
      createdAt: new Date(),
      updatedAt: null,
    };
    const variant2 = {
      id: "variant-new-2",
      productId: baseActiveProduct.id,
      axisValueKey: "value-2",
      itemId: `item-${baseActiveProduct.code}-002`,
      createdAt: new Date(),
      updatedAt: null,
    };
    spies.insert.mockReturnValueOnce(variant1);
    spies.insert.mockReturnValueOnce(variant2);

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await run(db, input, ctx, deps);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.variants).toHaveLength(2);
      expect(result.value.variants[0]).toEqual(variant1);
      expect(result.value.variants[1]).toEqual(variant2);
    }
  });
});
