import { createKyselyMock } from "@tailor-platform/sdk/vitest";
import { describe, expect, it } from "vitest";
import type { Namespace } from "../generated/kysely-tailordb";
import { DuplicateCodeError, MissingRequiredFieldError } from "../lib/errors.generated";
import { baseColorAttribute } from "../testing/fixtures";
import { run } from "./createProductAttribute";

describe("createProductAttribute", () => {
  it("returns error when code is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) => run(trx, { code: "", name: "Color" }));

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

  it("returns error when name is empty", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();

    const result = await mock.withTx((trx) => run(trx, { code: "COLOR", name: "" }));

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

  it("returns error when code already exists", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    mock.enqueueResults([baseColorAttribute]);

    const result = await mock.withTx((trx) => run(trx, { code: "COLOR", name: "Color" }));

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

  it("creates attribute successfully", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdAttribute = { ...baseColorAttribute, id: "new-attr-id" };

    mock.enqueueResults([], [createdAttribute]);

    const result = await mock.withTx((trx) => run(trx, { code: "COLOR", name: "Color" }));

    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.productAttribute.code).toBe("COLOR");
    }
    expect(mock.inserts.length).toBeGreaterThan(0);
  });

  it("passes custom fields through to insert", async () => {
    const mock = createKyselyMock<Namespace["main-db"]>();
    const createdAttribute = { ...baseColorAttribute, id: "new-attr-id", priority: 5 };

    mock.enqueueResults([], [createdAttribute]);

    await mock.withTx((trx) => run(trx, { code: "COLOR", name: "Color", priority: 5 }));

    expect(mock.inserts[0].insertValues()).toEqual(expect.objectContaining({ priority: 5 }));
  });
});
