export const runtime = "nodejs";
import { NextResponse } from "next/server";
import { createClient } from "@supabase/supabase-js";
import { SESClient, SendEmailCommand } from "@aws-sdk/client-ses";

function getOrigin(req: Request) {
  try { const u = new URL(req.url); return `${u.protocol}//${u.host}`; } catch { return process.env.NEXT_PUBLIC_SITE_URL || ""; }
}

async function sendWithSES(to: string, subject: string, html: string, text: string) {
  const region = process.env.AWS_REGION || "eu-west-3";
  const from = process.env.AWS_SES_FROM; // ex: "Espace Paie Odentas <noreply@odentas.fr>"
  if (!from) throw new Error("Missing AWS_SES_FROM");

  const ses = new SESClient({ region });
  const cmd = new SendEmailCommand({
    Destination: { ToAddresses: [to] },
    Source: from,
    Message: {
      Subject: { Data: subject, Charset: "UTF-8" },
      Body: {
        Html: { Data: html, Charset: "UTF-8" },
        Text: { Data: text, Charset: "UTF-8" },
      },
    },
  });
  await ses.send(cmd);
}

export async function POST(req: Request) {
  try {
    const { email, redirectTo } = await req.json();
    if (!email) return NextResponse.json({ error: "missing_email" }, { status: 400 });

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

    const admin = createClient(supabaseUrl, serviceKey, { auth: { autoRefreshToken: false, persistSession: false } });
    const base = process.env.NEXT_PUBLIC_SITE_URL || getOrigin(req);
    const toUrl = redirectTo || `${base}/set-password`;

    // 1) Tenter une INVITATION d'abord (si l'utilisateur n'existe pas). Si déjà inscrit → erreur "already registered" (422) et on bascule en recovery.
    const invite = await admin.auth.admin.inviteUserByEmail(email, { redirectTo: toUrl });
    const already = invite.error && (
      /already\s+registered|already\s+exists|user\s+exists/i.test(String(invite.error.message)) || invite.error.status === 422
    );

    let linkType: "invite" | "recovery" = "invite";
    if (invite.error && !already) {
      // autre erreur Supabase (hors "already registered") → on arrête
      return NextResponse.json({ error: "supabase_invite_error", message: invite.error.message }, { status: 400 });
    }
    if (already) {
      linkType = "recovery";
    }

    // 2) Générer un lien d'action (sans envoyer d'e-mail via Supabase)
    let gen = await admin.auth.admin.generateLink({
      type: linkType as any,
      email,
      options: { redirectTo: toUrl },
    });

    const pickActionLink = (out: any) => out?.data?.action_link || out?.data?.properties?.action_link || null;

    let actionLink = pickActionLink(gen);

    if (gen.error || !actionLink) {
      // Fallback: some projects expose action_link under data.properties or not at all for recovery/invite → try MAGIC LINK
      const magic = await admin.auth.admin.generateLink({
        type: "magiclink" as any,
        email,
        options: { redirectTo: toUrl },
      });
      actionLink = pickActionLink(magic);
      if (magic.error || !actionLink) {
        const details = magic.error?.message || gen.error?.message || "no action_link";
        return NextResponse.json({ error: "supabase_generate_error", message: details }, { status: 400 });
      }
      gen = magic;
      linkType = "invite"; // UX label remains correct (user will set password after sign-in)
    }

    // Dev diagnostics
    if (process.env.NODE_ENV !== 'production' || process.env.AUTH_BYPASS === '1') {
      console.log('[send-link] type=', linkType, 'redirectTo=', toUrl, 'action_link=', actionLink);
    }

    // 3) Envoi de l'e-mail via **AWS SES**
    const subject = linkType === "invite"
      ? "Créez votre mot de passe – Espace Paie"
      : "Définissez / réinitialisez votre mot de passe – Espace Paie";

    const html = `
      <div style="font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif; font-size: 16px; line-height: 1.5; color:#0f172a">
        <p>Bonjour,</p>
        <p>Cliquez sur le bouton ci-dessous pour ${linkType === "invite" ? "créer" : "définir"} votre mot de passe :</p>
        <p><a href="${actionLink}" style="display:inline-block;padding:12px 18px;background:#2563eb;color:#fff;border-radius:8px;text-decoration:none">Continuer</a></p>
        <p>Ou copiez/collez ce lien dans votre navigateur :</p>
        <p><a href="${actionLink}">${actionLink}</a></p>
        <p style="color:#64748b;font-size:12px">Si vous n’êtes pas à l’origine de cette demande, ignorez cet email.</p>
      </div>
    `;
    const text = `Bonjour,\n\nOuvrez ce lien pour ${linkType === "invite" ? "créer" : "définir"} votre mot de passe :\n${actionLink}\n\nSi vous n’êtes pas à l’origine de cette demande, ignorez cet email.`;

    await sendWithSES(email, subject, html, text);

    // 4) En dev, renvoyer le lien pour tester sans e-mail
    const isDev = process.env.NODE_ENV !== "production" || process.env.AUTH_BYPASS === "1";
    return NextResponse.json({ ok: true, type: linkType, email, redirectTo: toUrl, ...(isDev ? { debug_action_link: actionLink } : {}) }, { status: 200 });
  } catch (e: any) {
    return NextResponse.json({ error: "server_error", message: e?.message || "unknown" }, { status: 500 });
  }
}