import { authenticate } from "../shopify.server";
import { createPersoVariant } from "../utils/persoVariant.server";

/* POST /apps/personnalisateur/variant
   Corps : { baseVariantId, perso } — `perso` est l'objet `_perso` du builder.
   Réponse : { variantId, price } — la variante à ajouter au panier, créée au
   prix recalculé côté serveur (voir app/utils/persoVariant.server.js). */

const json = (body, status = 200) =>
  new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });

export async function action({ request }) {
  if (request.method !== "POST") return json({ error: "Méthode non autorisée" }, 405);

  let admin, session;
  try {
    ({ admin, session } = await authenticate.public.appProxy(request));
  } catch {
    return json({ error: "Proxy non autorisé" }, 401);
  }
  if (!admin || !session) return json({ error: "Application non installée sur cette boutique" }, 401);

  let body;
  try {
    body = await request.json();
  } catch {
    return json({ error: "Requête invalide" }, 400);
  }
  const { baseVariantId, perso } = body || {};
  if (!baseVariantId || !perso || typeof perso !== "object") {
    return json({ error: "baseVariantId et perso sont requis" }, 400);
  }

  try {
    const result = await createPersoVariant(admin, session.shop, { baseVariantId, perso });
    return json(result);
  } catch (error) {
    /* GraphqlQueryError : le détail utile est dans error.body (erreurs GraphQL) */
    const detail = error?.body?.errors?.graphQLErrors?.map((e) => e.message).join(" ")
      || error?.body?.errors?.message || "";
    console.error("[PersoVariant]", error?.message || error, detail);
    /* 200 + { error } : le proxy Shopify remplace le corps des réponses 5xx,
       le builder n'aurait alors aucun message à afficher. */
    return json({ error: (error?.message || "Erreur lors de la création de la variante") + (detail ? " — " + detail : "") });
  }
}
