<?php
if (!defined('ABSPATH'))
  exit;

use AC_SYNC\Includes\Classes\Api\Action_Wear_Api_Route;
use AC_SYNC\Includes\Classes\Api\Action_Wear_API_Response as ApiResponse;
use AC_SYNC\Includes\Classes\Product\Action_Wear_Product as Product;
use AC_SYNC\Includes\Classes\Logger\Action_Wear_Log as Log;

$route = new Action_Wear_Api_Route("/rebuild_category_product_relations");
$route->setMethods("POST");

$route->setCallback(function () {
  $response = new ApiResponse();

  $apikey = get_option('_ACTIONWEAR_APIKEY');
  if (empty($apikey)) {
    $response->fail("No API key configured");
    return $response->getResponse();
  }

  @set_time_limit(300);
  @ini_set('memory_limit', '512M');

  try {
    Product::generateProducts();
    Log::write("Rebuilt category-product relations via generateProducts()", Log::INFO, Log::CONTEXT_GENERAL);

    $response->success([
      "success" => true,
      "message" => "Relazioni prodotto-categoria ricostruite con successo"
    ]);
  } catch (\Throwable $e) {
    Log::write("Failed to rebuild category-product relations: " . $e->getMessage(), Log::ERROR, Log::CONTEXT_GENERAL);
    $response->fail($e->getMessage());
  }

  return $response->getResponse();
});

$route->registerRoute();
