import { NextRequest, NextResponse } from 'next/server';

interface Affiliate {
  id: number;
  name: string;
  country: string;
  verified: number;
  created_at: string;
  updated_at: string;
}

interface Pagination {
  current_page: number;
  last_page: number;
  per_page: number;
  total: number;
  from: number | null;
  to: number | null;
  has_more_pages: boolean;
  next_page_url: string | null;
  prev_page_url: string | null;
}

interface ApiResponse {
  affiliates: Affiliate[];
  pagination: Pagination;
}

export async function GET(request: NextRequest) {
  try {
    // Récupérer le token d'authentification
    const authToken = request.cookies.get('auth_token');

    if (!authToken) {
      return NextResponse.json(
        { error: 'Authentication token not found' },
        { status: 401 }
      );
    }

    // Récupérer les paramètres de pagination de la requête
    const searchParams = request.nextUrl.searchParams;
    const page = searchParams.get('page') || '1';

    // Construire l'URL avec les paramètres de pagination
    const apiUrl = `${process.env.LARAVEL_API_URL}/owa-spaces/my-affiliates?page=${page}`;

    // Appeler l'API Laravel
    const response = await fetch(apiUrl, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${authToken.value}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      // Gérer les erreurs spécifiques
      if (response.status === 401) {
        return NextResponse.json(
          { error: 'Unauthorized - Invalid authentication token' },
          { status: 401 }
        );
      }

      const errorData = await response.json().catch(() => ({}));
      return NextResponse.json(
        { 
          error: 'Failed to fetch affiliates',
          details: errorData
        },
        { status: response.status }
      );
    }

    // Parser la réponse JSON
    const data: ApiResponse = await response.json();

    // Retourner les données formatées
    return NextResponse.json({
      success: true,
      data: data.affiliates,
      pagination: data.pagination
    });

  } catch (error) {
    console.error('Error fetching affiliates:', error);
    return NextResponse.json(
      { 
        error: 'Server error while fetching affiliates',
        details: error instanceof Error ? error.message : 'Unknown error'
      },
      { status: 500 }
    );
  }
}
