import { createContext } from "@tailor-platform/erp-kit/app";
import { createResolver, t } from "@tailor-platform/sdk";
import { getDB } from "@/generated/kysely-tailordb";
import { pmModules } from "@/modules";

export default createResolver({
  name: "createAttribute",
  operation: "mutation",
  input: {
    code: t.string().description("Attribute code"),
    name: t.string().description("Attribute name"),
    valueLabels: t.string({ array: true, optional: true }).description("Initial value labels"),
  },
  body: async (context) => {
    const db = getDB("main-db");
    const result = await db.transaction().execute(async (trx) => {
      const cmdResult = await pmModules.commands.createProductAttribute(
        trx,
        {
          code: context.input.code,
          name: context.input.name,
        },
        createContext(context),
      );
      if (!cmdResult.ok) {
        switch (cmdResult.error.code) {
          case "PRODUCT_MANAGEMENT_DUPLICATE_CODE":
            throw new Error(`An attribute with code ${context.input.code} already exists`);
          case "PRODUCT_MANAGEMENT_MISSING_REQUIRED_FIELD":
            throw new Error(`Missing required field: ${cmdResult.error.message}`);
          case "INSUFFICIENT_PERMISSION":
            throw cmdResult.error;
          default:
            throw cmdResult.error satisfies never;
        }
      }
      for (const label of context.input.valueLabels ?? []) {
        const valResult = await pmModules.commands.createProductAttributeValue(
          trx,
          { attributeId: cmdResult.value.productAttribute.id, label },
          createContext(context),
        );
        if (!valResult.ok) {
          switch (valResult.error.code) {
            case "PRODUCT_MANAGEMENT_ATTRIBUTE_NOT_FOUND":
              throw new Error(`Attribute not found`);
            case "PRODUCT_MANAGEMENT_DUPLICATE_VALUE":
              throw new Error(`Duplicate value label: ${label}`);
            case "PRODUCT_MANAGEMENT_INVALID_LABEL":
              throw new Error(`Invalid label: ${label}`);
            case "INSUFFICIENT_PERMISSION":
              throw valResult.error;
            default:
              throw valResult.error satisfies never;
          }
        }
      }

      return {
        id: cmdResult.value.productAttribute.id,
        code: cmdResult.value.productAttribute.code,
        name: cmdResult.value.productAttribute.name,
      };
    });

    return result;
  },
  output: t
    .object({
      id: t.uuid().description("Attribute ID"),
      code: t.string().description("Attribute code"),
      name: t.string().description("Attribute name"),
    })
    .description("Created attribute"),
});
