// app/api/appapis/applications/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
import pool from '../../../../lib/db/db';
import { RowDataPacket } from 'mysql2';

interface TokenInterface {
  id: number;
  userId?: number;
  email?: string;
  role?: string;
}


// Handle OPTIONS for CORS preflight
export async function OPTIONS() {
  return NextResponse.json({}, { 
    status: 200
  });
}

export async function GET(request: NextRequest) {
  const connection = await pool.getConnection();

  try {
    // Get token from Authorization header
    const authHeader = request.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json({
        success: false,
        message: "No valid authorization header found"
      }, { 
        status: 401
      });
    }

    const token = authHeader.substring(7);
    
    // Verify token to get student ID
    const authResult = await verifyAuthentication(token);
    
    if (authResult instanceof NextResponse) {
      return authResult;
    }
    
    const decoded = authResult as TokenInterface;
    
    if (!decoded || !decoded.id) {
      return NextResponse.json({
        success: false,
        message: "Invalid token - no user ID found"
      }, { 
        status: 401
      });
    }

    const studentId = decoded.id; // Get student ID from token

    // EXACTLY your working query - unchanged
    const [applications] = await connection.query<RowDataPacket[]>(
      `SELECT 
        sa.*,
        CASE 
          WHEN sa.type = 'university' AND sa.apply_id IS NOT NULL THEN u.slug
          ELSE NULL
        END as university_slug
       FROM search_apply_now sa
       LEFT JOIN university_details u ON sa.type = 'university' AND sa.apply_id = u.id
       WHERE sa.user_id = ?
       ORDER BY sa.created_at DESC`,
      [studentId]
    );

    return NextResponse.json({ 
      success: true,
      applications: applications 
    }, { 
      status: 200
    });

  } catch (error) {
    console.error('Error fetching applications:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: 'Internal server error' 
      },
      { 
        status: 500
      }
    );
  } finally {
    connection.release();
  }
}