import { NextResponse } from "next/server";
import { createClient } from "@supabase/supabase-js";
import { sendPasswordCreatedEmail } from "@/lib/emailMigrationHelpers";

export async function POST(req: Request) {
  try {
    const auth = req.headers.get("authorization") || "";
    const token = auth.toLowerCase().startsWith("bearer ") ? auth.slice(7) : null;
    if (!token) {
      return NextResponse.json({ error: "missing_token" }, { status: 401 });
    }

    const { newPassword } = await req.json();
    if (!newPassword || String(newPassword).length < 12) {
      return NextResponse.json({ error: "weak_password", message: "12 caractères minimum." }, { status: 400 });
    }

    const url = process.env.SUPABASE_URL!;
    const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY!;
    if (!url || !serviceKey) {
      return NextResponse.json({ error: "misconfigured_supabase" }, { status: 500 });
    }

    const admin = createClient(url, serviceKey);

    // Obtenir l'utilisateur depuis l'access token fourni
    const { data: userRes, error: getUserErr } = await admin.auth.getUser(token);
    if (getUserErr || !userRes?.user) {
      return NextResponse.json({ error: "invalid_token" }, { status: 401 });
    }

    const userId = userRes.user.id;

    // Mettre à jour le mot de passe via l'Admin API
    const { error: updErr } = await admin.auth.admin.updateUserById(userId, { 
      password: newPassword,
      user_metadata: { hasPassword: true }
    });
    if (updErr) {
      return NextResponse.json({ error: "update_failed", message: updErr.message }, { status: 400 });
    }

    // Email confirmation 'password created' (non-bloquant)
    try {
      const userEmail = userRes.user.email || undefined;
      const firstName = (userRes.user.user_metadata as any)?.first_name || undefined;
      if (userEmail) {
        await sendPasswordCreatedEmail(userEmail, { firstName });
      }
    } catch (e) {
      console.warn('⚠️ Envoi email mot de passe créé échoué (non-bloquant):', (e as any)?.message || e);
    }

    return NextResponse.json({ ok: true });
  } catch (e: any) {
    return NextResponse.json({ error: "server_error", message: e?.message || "unknown" }, { status: 500 });
  }
}