import { describe, expect, it } from "vitest";
import { createMockDb } from "../../../testing/index";
import { Transaction } 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 "./setProductAttributeAssignment";

describe("setProductAttributeAssignment", () => {
  it("returns error when product not found", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select.mockReturnValueOnce(undefined); // product not found

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseDraftProduct) // product found
      .mockReturnValueOnce(undefined); // attribute not found

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseDraftProduct) // product found
      .mockReturnValueOnce(baseColorAttribute) // attribute found
      .mockReturnValueOnce(undefined); // value not found

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseArchivedProduct) // product found (ARCHIVED)
      .mockReturnValueOnce(baseColorAttribute) // attribute found
      .mockReturnValueOnce(baseColorRed) // value found
      .mockReturnValueOnce([]); // no existing assignments

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    const existingAssignment = {
      ...baseAttributeAssignment,
      productId: baseDraftProduct.id,
      valueId: baseColorRed.id,
    };
    spies.select
      .mockReturnValueOnce(baseDraftProduct) // product found
      .mockReturnValueOnce(baseColorAttribute) // attribute found
      .mockReturnValueOnce(baseColorRed) // value found
      .mockReturnValueOnce([existingAssignment]); // existing assignments with matching valueId

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

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productAttributeAssignment).toEqual(existingAssignment);
    }
    // Should not insert or update
    expect(spies.insert).not.toHaveBeenCalled();
    expect(spies.update).not.toHaveBeenCalled();
  });

  it("returns error when adding new attribute to ACTIVE product", async () => {
    const { db, spies } = createMockDb<Transaction>();
    spies.select
      .mockReturnValueOnce(baseActiveProduct) // product found (ACTIVE)
      .mockReturnValueOnce(baseColorAttribute) // attribute found
      .mockReturnValueOnce(baseColorRed) // value found
      .mockReturnValueOnce([]); // no existing assignments for this attribute

    const result = await run(db, {
      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 { db, spies } = createMockDb<Transaction>();
    const newAssignment = {
      ...baseAttributeAssignment,
      id: "new-assignment-id",
      productId: baseDraftProduct.id,
      valueId: baseColorRed.id,
    };

    spies.select
      .mockReturnValueOnce(baseDraftProduct) // product found
      .mockReturnValueOnce(baseColorAttribute) // attribute found
      .mockReturnValueOnce(baseColorRed) // value found
      .mockReturnValueOnce([]); // no existing assignments
    spies.insert.mockReturnValue(newAssignment);

    const result = await run(db, {
      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(spies.insert).toHaveBeenCalled();
  });

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

    spies.select
      .mockReturnValueOnce(baseActiveProduct) // product found (ACTIVE)
      .mockReturnValueOnce(baseColorAttribute) // attribute found
      .mockReturnValueOnce(baseColorBlue) // value found (Blue)
      .mockReturnValueOnce([existingAssignment]); // existing: Red already assigned
    spies.insert.mockReturnValue(newAssignment);

    const result = await run(db, {
      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(spies.insert).toHaveBeenCalled();
  });
});
