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: "moveCategory",
  operation: "mutation",
  input: {
    id: t.uuid().description("Category ID"),
    // null means move to root
    newParentId: t.uuid({ optional: true }).description("New parent category ID"),
  },
  body: async (context) => {
    const db = getDB("main-db");
    const result = await db.transaction().execute(async (trx) => {
      const cmdResult = await pmModules.commands.moveProductCategory(
        trx,
        {
          id: context.input.id,
          newParentId: context.input.newParentId ?? null,
        },
        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_CIRCULAR_REFERENCE":
            throw new Error("Moving the category would create a circular reference");
          case "PRODUCT_MANAGEMENT_MAX_DEPTH_EXCEEDED":
            throw new Error("Maximum category depth exceeded");
          case "PRODUCT_MANAGEMENT_PARENT_NOT_FOUND":
            throw new Error(`Parent category ${context.input.newParentId} does not exist`);
          case "INSUFFICIENT_PERMISSION":
            throw cmdResult.error;
          default:
            throw cmdResult.error satisfies never;
        }
      }
      return {
        id: cmdResult.value.category.id,
      };
    });

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