// app/api/frontend/consultant/consultantdashboard/student/edit/[id]/route.ts

import { NextRequest, NextResponse } from 'next/server';
import { EditStudentFormSchema } from '../../../../../../../../validations/studentValidation';
import pool from '../../../../../../../../lib/db/db';
import { verifyAuthentication } from '../../../../../../../utils/verifyAuthentication';
import { ResultSetHeader } from 'mysql2';

export async function PUT(request: NextRequest, { params }: any) {
    const connection = await pool.getConnection();

    try {
        const token = request.cookies.get('university-token')?.value || null;
        const decoded = await verifyAuthentication(token);

        if (!decoded || decoded instanceof NextResponse || decoded.role !== 'consultant') {
            return NextResponse.json(
                { success: false, message: 'Unauthorized' },
                { status: 401 }
            );
        }

        const applicationId = Number(params.id);
        if (isNaN(applicationId)) {
            return NextResponse.json(
                { success: false, message: 'Invalid student ID' },
                { status: 400 }
            );
        }

        const body = await request.json();
        const parsed = EditStudentFormSchema.safeParse(body);

        if (!parsed.success) {
            return NextResponse.json(
                {
                    success: false,
                    message: 'Validation failed',
                    errors: parsed.error.errors.map(e => ({
                        field: e.path.join('.'),
                        message: e.message
                    }))
                },
                { status: 400 }
            );
        }

        const data = parsed.data;

        await connection.beginTransaction();

        const updates: string[] = [];
        const values: any[] = [];

        if (data.name) updates.push('name = ?'), values.push(data.name);
        if (data.passportNumber) updates.push('passport_number = ?'), values.push(data.passportNumber);
        if (data.course) updates.push('course_doc = ?'), values.push(data.course);
        if (data.country) updates.push('intrested_country_doc = ?'), values.push(data.country);

        if (data.files) {
            const f = data.files;
            if (f.passport) updates.push('passport_doc = ?'), values.push(f.passport);
            if (f.photo) updates.push('photo_doc = ?'), values.push(f.photo);
            if (f.educationalDegree) updates.push('educational_degree_doc = ?'), values.push(f.educationalDegree);
            if (f.educationalCertificate) updates.push('educational_certificate_doc = ?'), values.push(f.educationalCertificate);
            if (f.recommendationLetter !== undefined)
                updates.push('recomendation_letter_doc = ?'), values.push(f.recommendationLetter || null);
            if (f.studyPlan !== undefined)
                updates.push('study_plan = ?'), values.push(f.studyPlan || null);
            if (f.ieltsOrEnglishProficiency !== undefined)
                updates.push('ielts_english_proficiency_letter = ?'), values.push(f.ieltsOrEnglishProficiency || null);
        }

        if (!updates.length) {
            await connection.rollback();
            return NextResponse.json(
                { success: false, message: 'No fields to update' },
                { status: 400 }
            );
        }

        updates.push('updated_at = NOW()');

        const query = `
            UPDATE cstudents
            SET ${updates.join(', ')}
            WHERE id = ? AND consultant_id = ?
        `;

        values.push(applicationId, decoded.id);

        const [result] = await connection.execute<ResultSetHeader>(query, values);

        if (!result.affectedRows) {
            await connection.rollback();
            return NextResponse.json(
                { success: false, message: 'Update failed' },
                { status: 500 }
            );
        }

        await connection.commit();

        return NextResponse.json({
            success: true,
            message: 'Student application updated successfully'
        });

    } catch (error) {
        await connection.rollback();
        return NextResponse.json(
            { success: false, message: 'Internal server error' },
            { status: 500 }
        );
    } finally {
        connection.release();
    }
}
