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: "deleteCategory",
  operation: "mutation",
  input: {
    id: t.uuid().description("Category ID"),
  },
  body: async (context) => {
    const db = getDB("main-db");
    const result = await db.transaction().execute(async (trx) => {
      const cmdResult = await pmModules.commands.deleteProductCategory(
        trx,
        { id: context.input.id },
        createContext(context),
      );
      if (!cmdResult.ok) {
        switch (cmdResult.error.code) {
          case "PRODUCT_MANAGEMENT_CATEGORY_NOT_FOUND":
            throw new Error(`Category ${context.input.id} does not exist`);
          case "PRODUCT_MANAGEMENT_HAS_CHILDREN":
            throw new Error("Category has child categories — remove them first");
          case "PRODUCT_MANAGEMENT_HAS_ASSIGNMENTS":
            throw new Error("Category has product assignments — remove them first");
          case "INSUFFICIENT_PERMISSION":
            throw cmdResult.error;
          default:
            throw cmdResult.error satisfies never;
        }
      }
      return {
        id: cmdResult.value.id,
      };
    });

    return result;
  },
  output: t.object({
    id: t.uuid().description("Deleted category ID"),
  }),
});
