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

export async function GET(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 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);

    const { data: userRes, error: getUserErr } = await admin.auth.getUser(token);
    if (getUserErr || !userRes?.user) {
      return NextResponse.json({ error: "invalid_token" }, { status: 401 });
    }

    // Vérifier dans user_metadata si l'utilisateur a un mot de passe défini
    const hasPassword = !!userRes.user.user_metadata?.hasPassword;
    return NextResponse.json({ hasPassword });
  } catch (e: any) {
    return NextResponse.json({ error: "server_error", message: e?.message || "unknown" }, { status: 500 });
  }
}