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: "generateVariants",
  operation: "mutation",
  input: {
    productId: t.uuid().description("Product ID"),
  },
  body: async (context) => {
    const db = getDB("main-db");
    const result = await db.transaction().execute(async (trx) => {
      const cmdResult = await pmModules.commands.generateVariants(
        trx,
        {
          productId: context.input.productId,
        },
        createContext(context),
      );
      if (!cmdResult.ok) {
        switch (cmdResult.error.code) {
          case "PRODUCT_MANAGEMENT_PRODUCT_NOT_FOUND":
            throw new Error(`Product not found: ${context.input.productId}`);
          case "PRODUCT_MANAGEMENT_INVALID_PRODUCT_STATUS":
            throw new Error(
              `Invalid product status for variant generation: ${cmdResult.error.message}`,
            );
          case "PRODUCT_MANAGEMENT_NO_VARIANT_AXES":
            throw new Error("Product has no variant axes defined");
          case "PRODUCT_MANAGEMENT_ATTRIBUTE_NOT_FOUND":
            throw new Error(`Attribute not found: ${cmdResult.error.message}`);
          case "PRODUCT_MANAGEMENT_ATTRIBUTE_VALUE_NOT_FOUND":
            throw new Error(`Attribute value not found: ${cmdResult.error.message}`);
          case "PRODUCT_MANAGEMENT_ITEM_CREATION_FAILED":
            throw new Error(`Failed to create variant items: ${cmdResult.error.message}`);
          case "INSUFFICIENT_PERMISSION":
            throw cmdResult.error;
          default:
            throw cmdResult.error satisfies never;
        }
      }
      return {
        generatedCount: String(cmdResult.value.variants.length),
      };
    });

    return result;
  },
  output: t
    .object({
      generatedCount: t.string().description("Number of generated variants"),
    })
    .description("Generated variants result"),
});
