import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import {
  ProductNotFoundError,
  AttributeNotFoundError,
  ProductArchivedError,
  AxisStructureLockedError,
  InvalidValueError,
} from "../lib/errors.generated";
import {
  baseDraftProduct,
  baseActiveProduct,
  baseArchivedProduct,
  baseColorAttribute,
  baseColorRed,
  baseColorBlue,
  baseAttributeAssignment,
} from "../testing/fixtures";
import { run } from "./assignAttributeValueToProduct";

describe("assignAttributeValueToProduct", () => {
  it("returns error when product not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([]);

    const result = await mock.withTx((trx) =>
      run(trx, {
        productId: "nonexistent",
        attributeId: "attr-1",
        valueId: "value-1",
      }),
    );

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

  it("returns error when attribute not found", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftProduct], []);

    const result = await mock.withTx((trx) =>
      run(trx, {
        productId: baseDraftProduct.id,
        attributeId: "nonexistent",
        valueId: "value-1",
      }),
    );

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

  it("returns error when value not found for attribute", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseDraftProduct], [baseColorAttribute], []);

    const result = await mock.withTx((trx) =>
      run(trx, {
        productId: baseDraftProduct.id,
        attributeId: baseColorAttribute.id,
        valueId: "invalid-value-id",
      }),
    );

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

  it("returns error when product is ARCHIVED", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseArchivedProduct], [baseColorAttribute], [baseColorRed], []);

    const result = await mock.withTx((trx) =>
      run(trx, {
        productId: baseArchivedProduct.id,
        attributeId: baseColorAttribute.id,
        valueId: baseColorRed.id,
      }),
    );

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

  it("returns existing assignment when exact triple already exists (idempotent no-op)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const existingAssignment = {
      ...baseAttributeAssignment,
      productId: baseDraftProduct.id,
      valueId: baseColorRed.id,
    };
    mock.enqueueResults(
      [baseDraftProduct],
      [baseColorAttribute],
      [baseColorRed],
      [existingAssignment],
    );

    const result = await mock.withTx((trx) =>
      run(trx, {
        productId: baseDraftProduct.id,
        attributeId: baseColorAttribute.id,
        valueId: baseColorRed.id,
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productAttributeAssignment).toEqual(existingAssignment);
    }
    expect(mock.inserts).toHaveLength(0);
    expect(mock.updates).toHaveLength(0);
  });

  it("returns error when adding new attribute to ACTIVE product", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseActiveProduct], [baseColorAttribute], [baseColorRed], []);

    const result = await mock.withTx((trx) =>
      run(trx, {
        productId: baseActiveProduct.id,
        attributeId: baseColorAttribute.id,
        valueId: baseColorRed.id,
      }),
    );

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

  it("creates new assignment on DRAFT product", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const newAssignment = {
      ...baseAttributeAssignment,
      id: "new-assignment-id",
      productId: baseDraftProduct.id,
      valueId: baseColorRed.id,
    };

    mock.enqueueResults(
      [baseDraftProduct],
      [baseColorAttribute],
      [baseColorRed],
      [],
      [newAssignment],
    );

    const result = await mock.withTx((trx) =>
      run(trx, {
        productId: baseDraftProduct.id,
        attributeId: baseColorAttribute.id,
        valueId: baseColorRed.id,
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productAttributeAssignment.productId).toBe(baseDraftProduct.id);
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("adds new value to existing attribute on ACTIVE product (additive-only)", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const existingAssignment = {
      ...baseAttributeAssignment,
      productId: baseActiveProduct.id,
      valueId: baseColorRed.id,
    };
    const newAssignment = {
      ...baseAttributeAssignment,
      id: "assignment-2",
      productId: baseActiveProduct.id,
      valueId: baseColorBlue.id,
    };

    mock.enqueueResults(
      [baseActiveProduct],
      [baseColorAttribute],
      [baseColorBlue],
      [existingAssignment],
      [newAssignment],
    );

    const result = await mock.withTx((trx) =>
      run(trx, {
        productId: baseActiveProduct.id,
        attributeId: baseColorAttribute.id,
        valueId: baseColorBlue.id,
      }),
    );

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productAttributeAssignment.valueId).toBe(baseColorBlue.id);
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });
});
