import { NextResponse } from "next/server";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { sendUniversalEmailV2 } from "@/lib/emailTemplateService";

export const dynamic = "force-dynamic";

// GET: Récupérer les parrainages de l'utilisateur ou d'une org (staff)
export async function GET(req: Request) {
  const sb = createRouteHandlerClient({ cookies });
  
  const { data: { user } } = await sb.auth.getUser();
  if (!user) {
    return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
  }
  
  const { searchParams } = new URL(req.url);
  const orgIdParam = searchParams.get("org_id");
  
  // Vérifier si l'utilisateur est staff
  const { data: staffData } = await sb
    .from("staff_users")
    .select("is_staff")
    .eq("user_id", user.id)
    .maybeSingle();
  
  const isStaff = !!staffData?.is_staff;
  
  let organizationId: string | null = null;
  
  if (isStaff && orgIdParam) {
    // Staff : utiliser l'org_id fourni en paramètre
    organizationId = orgIdParam;
  } else if (isStaff) {
    // Staff sans org_id : ne rien retourner
    return NextResponse.json({ referrals: [] });
  } else {
    // Client : récupérer son organisation
    const { data: memberData } = await sb
      .from("organization_members")
      .select("org_id")
      .eq("user_id", user.id)
      .eq("revoked", false)
      .maybeSingle();
    
    if (!memberData?.org_id) {
      return NextResponse.json({ error: "Organisation introuvable" }, { status: 404 });
    }
    
    organizationId = memberData.org_id;
  }
  
  // Récupérer les parrainages de cette organisation
  const { data: referrals, error } = await sb
    .from("referrals")
    .select("*")
    .eq("referrer_org_id", organizationId)
    .order("created_at", { ascending: false });
  
  if (error) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
  
  return NextResponse.json({ referrals });
}

// POST: Créer un nouveau parrainage et envoyer l'email
export async function POST(req: Request) {
  const sb = createRouteHandlerClient({ cookies });
  
  const { data: { user } } = await sb.auth.getUser();
  if (!user) {
    return NextResponse.json({ error: "Non authentifié" }, { status: 401 });
  }
  
  try {
    const body = await req.json();
    const {
      referrer_name,
      referee_name,
      referee_email,
      personal_message,
    } = body;
    
    // Validation
    if (!referrer_name || !referee_name || !referee_email) {
      return NextResponse.json({ 
        error: "Tous les champs obligatoires doivent être remplis" 
      }, { status: 400 });
    }
    
    // Validation email
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(referee_email)) {
      return NextResponse.json({ 
        error: "Email invalide" 
      }, { status: 400 });
    }
    
    // Vérifier si l'utilisateur est staff
    const { data: staffData } = await sb
      .from("staff_users")
      .select("is_staff")
      .eq("user_id", user.id)
      .maybeSingle();
    
    const isStaff = !!staffData?.is_staff;
    
    console.log('[Referrals API] POST - User info:', {
      userId: user.id,
      isStaff,
      staffData
    });
    
    // Pour le staff, récupérer l'org_id depuis les params
    let orgId: string | null = null;
    
    if (isStaff) {
      const url = new URL(req.url);
      orgId = url.searchParams.get("org_id");
      
      console.log('[Referrals API] Staff mode:', {
        requestUrl: req.url,
        orgIdParam: orgId
      });
      
      if (!orgId) {
        return NextResponse.json({ 
          error: "L'org_id est requis pour le staff" 
        }, { status: 400 });
      }
    } else {
      // Pour les clients, récupérer l'org_id depuis organization_members
      const { data: memberData } = await sb
        .from("organization_members")
        .select("org_id")
        .eq("user_id", user.id)
        .eq("revoked", false)
        .maybeSingle();
      
      console.log('[Referrals API] Client mode:', {
        memberData
      });
      
      if (!memberData?.org_id) {
        return NextResponse.json({ error: "Organisation introuvable" }, { status: 404 });
      }
      
      orgId = memberData.org_id;
    }
    
    console.log('[Referrals API] Final orgId:', orgId);
    
    if (!orgId) {
      return NextResponse.json({ error: "Organisation introuvable" }, { status: 404 });
    }
    
    // Vérifier si un parrainage existe déjà pour cet email
    const { data: existing } = await sb
      .from("referrals")
      .select("id, status")
      .eq("referrer_org_id", orgId)
      .eq("referee_email", referee_email)
      .maybeSingle();
    
    if (existing && existing.status !== 'cancelled') {
      return NextResponse.json({ 
        error: "Un parrainage existe déjà pour cette adresse email" 
      }, { status: 400 });
    }
    
    // Créer le parrainage
    const { data: referral, error: insertError } = await sb
      .from("referrals")
      .insert({
        referrer_org_id: orgId,
        referrer_user_id: user.id,
        referee_name,
        referee_email,
        personal_message: personal_message || null,
        status: 'pending',
        created_by: user.id,
      })
      .select()
      .single();
    
    if (insertError) {
      console.error("Erreur création parrainage:", insertError);
      return NextResponse.json({ error: insertError.message }, { status: 500 });
    }
    
    // Récupérer le nom de l'organisation pour l'email
    const { data: orgData } = await sb
      .from("organizations")
      .select("name")
      .eq("id", orgId)
      .single();
    
    const organizationName = orgData?.name || "cette organisation";
    
    // Extraire les prénoms (premier mot du nom complet)
    const referrerFirstName = referrer_name.split(' ')[0];
    const refereeFirstName = referee_name.split(' ')[0];
    
    // Envoyer l'email via le service mail universel v2
    try {
      console.log('[Referrals API] Sending email with data:', {
        referrerFirstName,
        refereeFirstName,
        organizationName,
        hasPersonalMessage: !!personal_message
      });
      
      const messageId = await sendUniversalEmailV2({
        type: "referral",
        toEmail: referee_email,
        data: {
          referrer_first_name: referrerFirstName,
          referee_first_name: refereeFirstName,
          organization_name: organizationName,
          personal_message: personal_message || "",
        },
      });
      
      console.log('[Referrals API] Email sent successfully:', messageId);
      
      // Mettre à jour le statut et la date d'envoi
      await sb
        .from("referrals")
        .update({
          status: 'email_sent',
          email_sent_at: new Date().toISOString(),
        })
        .eq("id", referral.id);
      
      referral.status = 'email_sent';
      referral.email_sent_at = new Date().toISOString();
    } catch (emailError) {
      console.error("Erreur lors de l'envoi de l'email:", emailError);
      // On continue même si l'email échoue
    }
    
    return NextResponse.json({ referral });
  } catch (err) {
    console.error("Erreur POST /api/referrals:", err);
    return NextResponse.json({ error: "Erreur serveur" }, { status: 500 });
  }
}
