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: "updateProductCategories",
  operation: "mutation",
  input: {
    productId: t.uuid().description("Product ID"),
    categoryIds: t.uuid({ array: true }).description("Desired category IDs"),
  },
  body: async (context) => {
    const db = getDB("main-db");
    const result = await db.transaction().execute(async (trx) => {
      const ctx = createContext(context);

      const currentAssignments = await trx
        .selectFrom("ProductCategoryAssignment")
        .select("categoryId")
        .where("productId", "=", context.input.productId)
        .execute();

      const currentIds = new Set(currentAssignments.map((a) => a.categoryId));
      const desiredIds = new Set(context.input.categoryIds);

      const toAssign = [...desiredIds].filter((id) => !currentIds.has(id));
      const toRemove = [...currentIds].filter((id) => !desiredIds.has(id));

      for (const categoryId of toAssign) {
        const r = await pmModules.commands.assignProductToCategory(
          trx,
          { productId: context.input.productId, categoryId },
          ctx,
        );
        if (!r.ok) {
          switch (r.error.code) {
            case "PRODUCT_MANAGEMENT_PRODUCT_NOT_FOUND":
              throw new Error(`Product ${context.input.productId} does not exist`);
            case "PRODUCT_MANAGEMENT_CATEGORY_NOT_FOUND":
              throw new Error(`Category ${categoryId} does not exist`);
            case "INSUFFICIENT_PERMISSION":
              throw r.error;
            default:
              throw r.error satisfies never;
          }
        }
      }

      for (const categoryId of toRemove) {
        const r = await pmModules.commands.removeProductFromCategory(
          trx,
          { productId: context.input.productId, categoryId },
          ctx,
        );
        if (!r.ok) {
          switch (r.error.code) {
            case "PRODUCT_MANAGEMENT_ASSIGNMENT_NOT_FOUND":
              break;
            case "INSUFFICIENT_PERMISSION":
              throw r.error;
            default:
              throw r.error satisfies never;
          }
        }
      }

      return { productId: context.input.productId };
    });

    return { productId: result.productId };
  },
  output: t
    .object({
      productId: t.uuid().description("Product ID"),
    })
    .description("Product categories update result"),
});
