import { NextRequest, NextResponse } from 'next/server';
import { supabaseAdmin } from '@/lib/odentas-sign/supabase';

export const runtime = 'nodejs';

/**
 * GET /api/odentas-sign/requests/[id]/status
 * 
 * Récupère le statut d'une demande de signature (publique pour le monitoring)
 */
export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const requestId = params.id;

    // Récupérer la demande avec tous les signataires
    const { data: signRequest, error } = await supabaseAdmin
      .from('sign_requests')
      .select(`
        id,
        ref,
        title,
        status,
        created_at,
        source_s3_key,
        signers (
          id,
          role,
          name,
          email,
          signed_at,
          signature_image_s3
        )
      `)
      .eq('id', requestId)
      .single();

    if (error || !signRequest) {
      return NextResponse.json(
        { error: 'Demande non trouvée' },
        { status: 404 }
      );
    }

    // Calculer la progression
    const signers = Array.isArray(signRequest.signers) ? signRequest.signers : [];
    const totalSigners = signers.length;
    const signedCount = signers.filter((s: any) => s.signed_at !== null).length;
    const allSigned = signedCount === totalSigners && totalSigners > 0;

    return NextResponse.json({
      success: true,
      request: {
        id: signRequest.id,
        ref: signRequest.ref,
        title: signRequest.title,
        status: signRequest.status,
        created_at: signRequest.created_at,
      },
      signers: signers.map((s: any) => ({
        id: s.id,
        role: s.role,
        name: s.name,
        email: s.email,
        has_signed: s.signed_at !== null,
        signed_at: s.signed_at,
      })),
      progress: {
        total: totalSigners,
        signed: signedCount,
        percentage: totalSigners > 0 ? Math.round((signedCount / totalSigners) * 100) : 0,
        all_signed: allSigned,
      },
    });
  } catch (error) {
    console.error('Erreur GET status:', error);
    return NextResponse.json(
      { error: 'Erreur interne du serveur' },
      { status: 500 }
    );
  }
}
