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

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

export async function POST(req: Request) {
  try {
    const supabase = createRouteHandlerClient({ cookies });
    const { data: { session } } = await supabase.auth.getSession();
    
    if (!session) {
      return NextResponse.json({ error: 'unauthorized' }, { status: 401 });
    }

    const body = await req.json();
    const { organizationId, newMode } = body;

    if (!organizationId || !newMode) {
      return NextResponse.json({ error: 'missing_parameters' }, { status: 400 });
    }

    if (!['odentas', 'client'].includes(newMode.toLowerCase())) {
      return NextResponse.json({ error: 'invalid_mode' }, { status: 400 });
    }

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

    if (orgError || !orgData) {
      return NextResponse.json({ error: 'organization_not_found' }, { status: 404 });
    }

    const orgDetails = Array.isArray(orgData.organization_details)
      ? orgData.organization_details[0]
      : orgData.organization_details;

    const currentMode = orgDetails?.virements_salaires?.toLowerCase() || 'client';
    const targetMode = newMode.toLowerCase() === 'odentas' ? 'Odentas' : 'Client';

    // Vérifier que le mode change réellement
    if (currentMode === targetMode.toLowerCase()) {
      return NextResponse.json({ 
        error: 'no_change_needed',
        message: 'Le mode de gestion est déjà celui demandé'
      }, { status: 400 });
    }

    // Mettre à jour le mode de gestion
    const { error: updateError } = await supabase
      .from('organization_details')
      .update({ virements_salaires: targetMode })
      .eq('org_id', organizationId);

    if (updateError) {
      console.error('Erreur mise à jour virements_salaires:', updateError);
      return NextResponse.json({ error: 'update_failed' }, { status: 500 });
    }

    // Préparer les emails
    const orgName = orgData.structure_api || orgData.name;
    const emailClient = orgDetails?.email_notifs;
    const emailClientCC = orgDetails?.email_notifs_cc;

    // Importer le service d'email
    const { sendUniversalEmailV2 } = await import('@/lib/emailTemplateService');

    // Email au client
    if (emailClient) {
      const emailType = targetMode === 'Odentas' 
        ? 'virements-gestion-to-odentas' 
        : 'virements-gestion-to-client';

      const emailData = {
        organizationName: orgName,
        companyName: orgName,
        employerCode: orgDetails?.code_employeur || '—',
        handlerName: 'Renaud BREVIERE-ABRAHAM',
        gestionMode: targetMode === 'Odentas' ? 'Géré par Odentas' : 'Géré en autonomie',
        changeDate: new Date().toLocaleString('fr-FR', { 
          year: 'numeric', 
          month: 'long', 
          day: 'numeric',
          hour: '2-digit',
          minute: '2-digit'
        }),
        firstName: orgDetails?.prenom_contact || '',
        supportUrl: 'https://espace-paie.odentas.fr/support',
        step1: 'Réception de l\'appel à virement mensuel',
        step2: 'Virement unique vers Odentas',
        step3: 'Redistribution automatique aux salariés',
      };

      try {
        await sendUniversalEmailV2({
          type: emailType as any,
          toEmail: emailClient,
          ccEmail: emailClientCC || undefined,
          data: emailData
        });
      } catch (emailError) {
        console.error('Erreur envoi email client:', emailError);
        // Continue même si l'email échoue
      }
    }

    // Email interne à l'équipe Odentas
    const internalData = {
      organizationName: orgName,
      previousMode: currentMode,
      newMode: targetMode,
      changeDate: new Date().toLocaleString('fr-FR'),
    };

    try {
      await sendUniversalEmailV2({
        type: 'virements-gestion-internal',
        toEmail: 'paie@odentas.fr',
        data: internalData
      });
    } catch (emailError) {
      console.error('Erreur envoi email interne:', emailError);
      // Continue même si l'email échoue
    }

    return NextResponse.json({
      success: true,
      previousMode: currentMode,
      newMode: targetMode
    });

  } catch (error) {
    console.error('Error changing gestion mode:', error);
    return NextResponse.json({ 
      error: 'internal_server_error',
      message: error instanceof Error ? error.message : 'Unknown error'
    }, { status: 500 });
  }
}
