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: "updateCategory",
  operation: "mutation",
  input: {
    id: t.uuid().description("Category ID"),
    name: t.string().description("New category name"),
  },
  body: async (context) => {
    const db = getDB("main-db");
    const result = await db.transaction().execute(async (trx) => {
      const cmdResult = await pmModules.commands.updateProductCategory(
        trx,
        {
          id: context.input.id,
          name: context.input.name,
        },
        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_MISSING_REQUIRED_FIELD":
            throw new Error("Category name is required");
          case "INSUFFICIENT_PERMISSION":
            throw cmdResult.error;
          default:
            throw cmdResult.error satisfies never;
        }
      }
      return {
        id: cmdResult.value.category.id,
        name: cmdResult.value.category.name,
      };
    });

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