import { NextResponse } from "next/server"; import { createAdminClient } from "@/lib/supabase/server"; import { verifyAdmin, isAdminError } from "@/lib/admin"; import { stripe } from "@/lib/stripe/client"; import { getBaseUrl } from "@/lib/utils"; export const runtime = "nodejs"; // POST /api/admin/candidatures/[id]/approve - Approuver une candidature export async function POST( _request: Request, { params }: { params: Promise<{ id: string }> } ) { const auth = await verifyAdmin(); if (isAdminError(auth)) { return NextResponse.json({ error: auth.error }, { status: auth.status }); } const { id } = await params; const supabase = createAdminClient(); // Récupérer la candidature const { data: candidature, error: fetchError } = await supabase .from("candidatures") .select("*") .eq("id", id) .single(); if (fetchError || !candidature) { return NextResponse.json({ error: "Candidature introuvable." }, { status: 404 }); } const email = (candidature as Record).email as string; const firstname = (candidature as Record).firstname as string; const candidatureId = (candidature as Record).id as string; // Mettre à jour le statut const { error: updateError } = await supabase .from("candidatures") .update({ status: "approved" } as never) .eq("id", id); if (updateError) { return NextResponse.json({ error: updateError.message }, { status: 500 }); } // Générer le lien de paiement Stripe let checkoutUrl: string | null = null; let stripeError: string | null = null; if (process.env.STRIPE_SECRET_KEY && process.env.STRIPE_PRICE_ID) { try { const baseUrl = getBaseUrl(); const customers = await stripe.customers.list({ email, limit: 1 }); let customerId: string; if (customers.data.length > 0) { customerId = customers.data[0].id; } else { const customer = await stripe.customers.create({ email, metadata: { candidature_id: candidatureId }, }); customerId = customer.id; } const session = await stripe.checkout.sessions.create({ customer: customerId, mode: "subscription", payment_method_types: ["card"], line_items: [{ price: process.env.STRIPE_PRICE_ID, quantity: 1 }], metadata: { candidature_id: candidatureId, email }, success_url: `${baseUrl}/merci?session_id={CHECKOUT_SESSION_ID}`, cancel_url: `${baseUrl}/candidature`, allow_promotion_codes: true, billing_address_collection: "required", }); checkoutUrl = session.url; } catch (err) { stripeError = err instanceof Error ? err.message : "Erreur Stripe inconnue"; console.error("Erreur Stripe:", err); } } else { stripeError = "STRIPE_SECRET_KEY ou STRIPE_PRICE_ID non configuré."; } // Envoyer l'email (indépendamment de Stripe) let emailSent = false; let emailError: string | null = null; if (!process.env.RESEND_API_KEY) { emailError = "RESEND_API_KEY non configuré sur Vercel."; } else { try { const { Resend } = await import("resend"); const resend = new Resend(process.env.RESEND_API_KEY); const fromEmail = process.env.RESEND_FROM_EMAIL || "HookLab "; const paymentButton = checkoutUrl ? `Finaliser mon inscription` : `

Le lien de paiement sera envoyé séparément.

`; await resend.emails.send({ from: fromEmail, to: email, subject: `${firstname}, ta candidature HookLab est acceptée !`, html: `
H
HookLab

Félicitations ${firstname} !

Ta candidature a été acceptée

On a étudié ton profil et on pense que tu as le potentiel pour réussir sur TikTok Shop.

Pour accéder au programme et commencer ta formation, il te reste une dernière étape :

${paymentButton}

Ce qui t'attend :

Programme complet de 8 semaines
Accompagnement personnalisé
Accès à la communauté HookLab
Stratégies TikTok Shop éprouvées

Le paiement est 100% sécurisé via Stripe. Tu peux payer en 2 mensualités de 490€. Si tu as des questions, réponds directement à cet email.

HookLab - Programme TikTok Shop

Enguerrand Ozano · SIREN 994538932

`, }); emailSent = true; } catch (err) { emailError = err instanceof Error ? err.message : "Erreur envoi email"; console.error("Erreur envoi email approbation:", err); } } return NextResponse.json({ success: true, checkoutUrl, emailSent, emailError, stripeError, message: [ "Candidature approuvée.", checkoutUrl ? "Lien de paiement généré." : (stripeError || "Stripe non configuré."), emailSent ? "Email envoyé." : (emailError || "Email non envoyé."), ].join(" "), }); }