import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../../../lib/db/db';
import { verifyAuthentication } from '../../../../../utils/verifyAuthentication';
import { RowDataPacket } from 'mysql2';

export async function POST(request: NextRequest) {

    try{

        const token = request.cookies.get("university-token")?.value || null;
        const decoded = await verifyAuthentication(token);
    
        if (decoded instanceof NextResponse) {
            return NextResponse.json(
                {
                    success: false,
                    message: "You are not authorized to perform this action"
                },
                {
                    status: 401 // Unauthorized
                }
            );
        }
    
        if(decoded){
    
            if(decoded.role === "consultant")
            {
                const [rows] = await pool.query<RowDataPacket[]>("SELECT * FROM cstudents WHERE consultant_id = ? ORDER BY created_at DESC", [decoded.id])
                if(rows.length === 0)
                {
                    return NextResponse.json(
                        {
                            success: false,
                            message: "No data found"
                        },
                        {
                            status: 404
                        }
                    )
                }

                return NextResponse.json(
                    {
                        success: true,
                        message: "Data Found",
                        data: rows
                    },
                    {
                        status: 200
                    }
                )
            }
            else {
                return NextResponse.json(
                    {
                        success: false,
                        message: "You are not authorized to perform this action"
                    },
                    {
                        status: 401 // Unauthorized
                    }
                );
            }
        }
        else {
            return NextResponse.json(
                {
                    success: false,
                    message: "You are not authorized to perform this action"
                },
                {
                    status: 401 // Unauthorized
                }
            );
        }

    } catch (error) {

        console.error('Error adding student:', error);

        return NextResponse.json(
        { 
            success: false, 
            message: 'Internal server error',
            error: error instanceof Error ? error.message : 'Unknown error'
        },
        { status: 500 }
        );
    }

}