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

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

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

        if (decoded instanceof NextResponse || !decoded) {
            return NextResponse.json(
                {
                    success: false,
                    message: "You are not authorized to perform this action"
                },
                {
                    status: 401
                }
            );
        }

        if (decoded.role !== "consultant") {
            return NextResponse.json(
                {
                    success: false,
                    message: "You are not authorized to perform this action"
                },
                {
                    status: 401
                }
            );
        }

        await connection.beginTransaction();

        const body = await request.json();

        // Validate the request body with Zod
        const validationResult = CreateStudentFormSchema .safeParse(body);

        if (!validationResult.success) {
            // Format Zod errors into a user-friendly format
            const errors = validationResult.error.errors.map(err => ({
                field: err.path.join('.'),
                message: err.message
            }));

            return NextResponse.json(
                { 
                    success: false, 
                    message: 'Validation failed',
                    errors: errors
                },
                { status: 400 }
            );
        }

        // If validation passes, extract the validated data
        const validatedData = validationResult.data;

        // Check if all required files are present
        const requiredFiles = [
            'passport',
            'photo',
            'educationalDegree',
            'educationalCertificate',
            'recommendationLetter',
            'studyPlan',
            'ieltsOrEnglishProficiency'
        ];

        const missingFiles = requiredFiles.filter(fileField => 
            !validatedData.files[fileField] || validatedData.files[fileField] === ''
        );

        if (missingFiles.length > 0) {
            return NextResponse.json(
                {
                    success: false,
                    message: 'All files are required',
                    errors: missingFiles.map(field => ({
                        field: `files.${field}`,
                        message: `${field.replace(/([A-Z])/g, ' $1').toLowerCase()} is required`
                    }))
                },
                { status: 400 }
            );
        }

        const query = `
            INSERT INTO cstudents (
                name, 
                passport_number, 
                course_doc, 
                intrested_country_doc, 
                passport_doc, 
                photo_doc, 
                educational_degree_doc, 
                educational_certificate_doc, 
                recomendation_letter_doc, 
                study_plan, 
                ielts_english_proficiency_letter,
                consultant_id,
                created_at,
                updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
        `;

        // Prepare values for insertion
        const values = [
            validatedData.name,
            validatedData.passportNumber,
            validatedData.course,
            validatedData.country,
            validatedData.files.passport,
            validatedData.files.photo,
            validatedData.files.educationalDegree,
            validatedData.files.educationalCertificate,
            validatedData.files.recommendationLetter,
            validatedData.files.studyPlan,
            validatedData.files.ieltsOrEnglishProficiency,
            decoded.id
        ];

        // Execute the query
        const [result] = await connection.execute(query, values);

        const studentData = {
            name: validatedData.name,
            passport_number: validatedData.passportNumber,
            course_doc: validatedData.course,
            intrested_country_doc: validatedData.country,
            passport_doc: validatedData.files.passport,
            photo_doc: validatedData.files.photo,
            educational_degree_doc: validatedData.files.educationalDegree,
            educational_certificate_doc: validatedData.files.educationalCertificate,
            recomendation_letter_doc: validatedData.files.recommendationLetter,
            study_plan: validatedData.files.studyPlan,
            ielts_english_proficiency_letter: validatedData.files.ieltsOrEnglishProficiency,
            consultant_id: decoded.id
        };

        const insertId = (result as any).insertId;

        // Send to external CRM API
        const response = await fetch("https://crm-universitiespage.com/reactapis/api/website_consultants_Students/store", {
            method: "POST",
            body: JSON.stringify(studentData),
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `${process.env.CRM_API_KEY}`,
            },
        });

        const data = await response.json();

        if (data?.status_code !== 200) {
            await connection.rollback();
            return NextResponse.json(
                {
                    message: "Failed to submit your form. Please try again later.",
                    success: false
                },
                {
                    status: 500
                }
            );
        }

        await connection.commit();

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

    } catch (error) {
        await connection.rollback();
        console.error('Error adding student:', error);

        if (error instanceof SyntaxError) {
            return NextResponse.json(
                { 
                    success: false, 
                    message: 'Invalid JSON in request body' 
                },
                { status: 400 }
            );
        }

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