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: "createCategory",
  operation: "mutation",
  input: {
    code: t.string().description("Category code"),
    name: t.string().description("Category name"),
    parentId: t.uuid({ optional: true }).description("Parent category ID"),
  },
  body: async (context) => {
    const db = getDB("main-db");
    const result = await db.transaction().execute(async (trx) => {
      const cmdResult = await pmModules.commands.createProductCategory(
        trx,
        {
          code: context.input.code,
          name: context.input.name,
          parentId: context.input.parentId ?? undefined,
        },
        createContext(context),
      );
      if (!cmdResult.ok) {
        switch (cmdResult.error.code) {
          case "PRODUCT_MANAGEMENT_DUPLICATE_CODE":
            throw new Error(`A category with code "${context.input.code}" already exists`);
          case "PRODUCT_MANAGEMENT_MISSING_REQUIRED_FIELD":
            throw new Error("Category code and name are required");
          case "PRODUCT_MANAGEMENT_PARENT_NOT_FOUND":
            throw new Error(`Parent category ${context.input.parentId} does not exist`);
          case "PRODUCT_MANAGEMENT_MAX_DEPTH_EXCEEDED":
            throw new Error("Maximum category depth exceeded");
          case "INSUFFICIENT_PERMISSION":
            throw cmdResult.error;
          default:
            throw cmdResult.error satisfies never;
        }
      }
      return {
        id: cmdResult.value.productCategory.id,
        code: cmdResult.value.productCategory.code,
        name: cmdResult.value.productCategory.name,
      };
    });

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