// app/api/staff/clients/[id]/request-sepa-mandate/route.ts
import { NextResponse } from "next/server";
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { sendSepaMandateRequestEmail } from "@/lib/emailMigrationHelpers";

export const dynamic = 'force-dynamic';
export const revalidate = 0;
export const runtime = 'nodejs';

async function isStaffUser(supabase: any, userId: string): Promise<boolean> {
  try {
    const { data: staffRow } = await supabase
      .from('staff_users')
      .select('is_staff')
      .eq('user_id', userId)
      .maybeSingle();
    return !!staffRow?.is_staff;
  } catch {
    return false;
  }
}

export async function POST(req: Request, { params }: { params: { id: string } }) {
  try {
    console.log('[api/staff/clients/[id]/request-sepa-mandate] POST request for organization ID:', params.id);
    
    const supabase = createRouteHandlerClient({ cookies });
    const { data: { session } } = await supabase.auth.getSession();
    if (!session) return NextResponse.json({ error: 'unauthorized' }, { status: 401 });

    // Vérifier que l'utilisateur est staff
    const isStaff = await isStaffUser(supabase, session.user.id);
    if (!isStaff) {
      return NextResponse.json({ error: 'forbidden', message: 'Staff access required' }, { status: 403 });
    }

    // Récupérer les informations de l'organisation
    const { data: orgData, error: orgError } = await supabase
      .from('organizations')
      .select(`
        id,
        structure_api,
        organization_details(
          email_notifs,
          email_notifs_cc,
          prenom_contact,
          code_employeur
        )
      `)
      .eq('id', params.id)
      .single();

    if (orgError || !orgData) {
      console.error('[api/staff/clients/[id]/request-sepa-mandate] Organization error:', orgError);
      return NextResponse.json({ error: 'organization_not_found' }, { status: 404 });
    }

    const organizationDetails = Array.isArray(orgData.organization_details) 
      ? orgData.organization_details[0] 
      : orgData.organization_details;
    
    if (!organizationDetails.email_notifs) {
      return NextResponse.json({ error: 'no_notification_email' }, { status: 400 });
    }

    // Envoyer l'email de demande de mandat SEPA
    console.log('[api/staff/clients/[id]/request-sepa-mandate] Sending SEPA mandate request email...');
    
    const firstName = organizationDetails.prenom_contact || "";
    const organizationName = orgData.structure_api || "";
    
    await sendSepaMandateRequestEmail(
      organizationDetails.email_notifs,
      organizationDetails.email_notifs_cc,
      {
        firstName,
        organizationName,
        employerCode: organizationDetails.code_employeur || undefined,
        mandateLink: 'https://pay.gocardless.com/BRT0002PDGX37ZX'
      }
    );

    console.log('[api/staff/clients/[id]/request-sepa-mandate] SEPA mandate request email sent successfully');

    return NextResponse.json({
      success: true,
      message: 'Demande de mandat SEPA envoyée avec succès'
    });

  } catch (error) {
    console.error('[api/staff/clients/[id]/request-sepa-mandate] Error:', error);
    const message = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ 
      error: 'internal_server_error', 
      message 
    }, { status: 500 });
  }
}
