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

describe("generateVariants", () => {
  const ctx: CommandContext = {
    actorId: "test-actor",
    permissions: ["product-management:product: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 attributeValue = (id: string, label = id) => ({ id, label });
  const deps = {
    itemManagement: { createItem: mockCreateItem },
    skuStrategy,
  };

  it("should return ProductNotFoundError when product does not exist", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);
    const input: GenerateVariantsInput = { productId: "non-existent" };
    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftProduct]);
    const input: GenerateVariantsInput = { productId: baseDraftProduct.id };
    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveProduct], []);

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();
    const colorRedAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-1",
    };
    mock.enqueueResults([baseActiveProduct], [colorRedAssignment], []);

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();
    const colorRedAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-1",
    };
    mock.enqueueResults([baseActiveProduct], [colorRedAssignment], [baseColorAttribute], []);

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();
    const colorRedAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-1",
    };
    const existingVariant = {
      id: "variant-existing",
      productId: baseActiveProduct.id,
      axisValueKey: "value-1",
      itemId: "item-existing",
      createdAt: new Date(),
      updatedAt: null,
    };
    mock.enqueueResults(
      [baseActiveProduct],
      [colorRedAssignment],
      [baseColorAttribute],
      [attributeValue("value-1")],
      [existingVariant],
    );

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await mock.withTx((trx) => run(trx, 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(mock.inserts).toHaveLength(0);
  });

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

    const colorRedAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-1",
    };
    mock.enqueueResults(
      [baseActiveProduct],
      [colorRedAssignment],
      [baseColorAttribute],
      [attributeValue("value-1")],
      [],
    );

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

  it("should pass axis value labels to skuStrategy", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const labelAwareSkuStrategy = vi.fn(
      (code: string, _values: string[], _count: number, labels?: string[]) =>
        `${code}-${labels?.join("-") ?? "missing"}`,
    );
    const labelAwareDeps = {
      itemManagement: { createItem: mockCreateItem },
      skuStrategy: labelAwareSkuStrategy,
    };

    const colorBlackAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-color-black",
    };
    const sizeLargeAssignment = {
      ...baseAttributeAssignment,
      id: "assignment-size-large",
      attributeId: baseSizeAttribute.id,
      valueId: "value-size-large",
    };
    const variant = {
      id: "variant-new-1",
      productId: baseActiveProduct.id,
      axisValueKey: "value-color-black|value-size-large",
      itemId: `item-${baseActiveProduct.code}-BLK-L`,
      createdAt: new Date(),
      updatedAt: null,
    };
    mock.enqueueResults(
      [baseActiveProduct],
      [colorBlackAssignment, sizeLargeAssignment],
      [baseColorAttribute],
      [baseSizeAttribute],
      [attributeValue("value-color-black", "BLK"), attributeValue("value-size-large", "L")],
      [],
      [variant],
    );

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await mock.withTx((trx) => run(trx, input, ctx, labelAwareDeps));

    expect(result.ok).toBe(true);
    expect(labelAwareSkuStrategy).toHaveBeenCalledWith(
      baseActiveProduct.code,
      ["value-color-black", "value-size-large"],
      0,
      ["BLK", "L"],
    );
    expect(mock.inserts[0].insertValues()).toEqual(
      expect.objectContaining({
        itemId: `item-${baseActiveProduct.code}-BLK-L`,
      }),
    );
  });

  it("should generate multi-axis cartesian product variants", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    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",
    };
    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,
    };
    mock.enqueueResults(
      [baseActiveProduct],
      [colorRedAssignment, colorBlueAssignment, sizeSmallAssignment],
      [baseColorAttribute],
      [baseSizeAttribute],
      [attributeValue("value-1"), attributeValue("value-2"), attributeValue("value-3")],
      [],
      [variant1],
      [variant2],
    );

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();
    const colorRedAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-1",
    };
    const colorBlueAssignment = {
      ...baseAttributeAssignment,
      id: "assignment-2",
      valueId: "value-2",
    };
    const existingVariant = {
      id: "variant-existing",
      productId: baseActiveProduct.id,
      axisValueKey: "value-1",
      itemId: "item-existing",
      createdAt: new Date(),
      updatedAt: null,
    };
    const newVariant = {
      id: "variant-new-1",
      productId: baseActiveProduct.id,
      axisValueKey: "value-2",
      itemId: `item-${baseActiveProduct.code}-002`,
      createdAt: new Date(),
      updatedAt: null,
    };
    mock.enqueueResults(
      [baseActiveProduct],
      [colorRedAssignment, colorBlueAssignment],
      [baseColorAttribute],
      [attributeValue("value-1"), attributeValue("value-2")],
      [existingVariant],
      [newVariant],
    );

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await mock.withTx((trx) => run(trx, 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 mock = createKyselyMock<Namespace["main-db"]>();
    const colorRedAssignment = {
      ...baseAttributeAssignment,
      valueId: "value-1",
    };
    const colorBlueAssignment = {
      ...baseAttributeAssignment,
      id: "assignment-2",
      valueId: "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,
    };
    mock.enqueueResults(
      [baseActiveProduct],
      [colorRedAssignment, colorBlueAssignment],
      [baseColorAttribute],
      [attributeValue("value-1"), attributeValue("value-2")],
      [],
      [variant1],
      [variant2],
    );

    const input: GenerateVariantsInput = { productId: baseActiveProduct.id };
    const result = await mock.withTx((trx) => run(trx, 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);
    }
  });
});
