// app/api/frontend/userdashboard/submit-feedback/[id]/route.js
import pool from '../../../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket } from 'mysql2';
import jwt from 'jsonwebtoken';
import { z } from 'zod';

type PageProps = {
  params: Promise<{
    id: string;
  }>;
};

// Validation schema
const feedbackSchema = z.object({
  feedback: z.string()
    .min(10, 'Feedback must be at least 10 characters')
    .max(1000, 'Feedback cannot exceed 1000 characters')
});

export async function POST(
  req: NextRequest,
  { params }: PageProps
) {
  const connection = await pool.getConnection();
  
  try {
    const {id} = await params;
    const appointmentId = id;
    
    if (!appointmentId) {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Invalid appointment ID' },
        { status: 400 }
      );
    }

    // Get token from cookie
    const token = req.cookies.get('university-token')?.value;
    
    if (!token) {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Authentication required' },
        { status: 401 }
      );
    }

    // Verify token
    let decoded;
    try {
      decoded = jwt.verify(token, process.env.JWT_SECRET as string);
    } catch (err) {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Invalid or expired token' },
        { status: 401 }
      );
    }

    // Check if user is authorized (student)
    if (decoded.role !== 'student') {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Access denied. Only students can submit feedback.' },
        { status: 403 }
      );
    }

    const studentId = decoded.id;
    const body = await req.json();
    
    // Validate input
    const validatedData = feedbackSchema.parse(body);

    // Start transaction
    await connection.beginTransaction();

    // 1. Check if appointment exists and belongs to this student
    const [appointment] = await connection.query<RowDataPacket[]>(
      `SELECT fsbs.id, fsbs.status, fsbs.student_feedback,
              fsbs.foreign_student_id, fsbs.student_id as tutor_user_id
       FROM foreign_student_booked_sessions fsbs
       INNER JOIN foreign_students fs ON fsbs.foreign_student_id = fs.id
       WHERE fsbs.id = ? AND fsbs.student_id = ?`,
      [appointmentId, studentId]
    );

    if (appointment.length === 0) {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Appointment not found or access denied' },
        { status: 404 }
      );
    }

    const currentAppointment = appointment[0];

    // 2. Check if appointment is completed
    if (currentAppointment.status !== 'completed') {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { 
          success: false, 
          message: 'Feedback can only be submitted for completed sessions' 
        },
        { status: 400 }
      );
    }

    // 3. Check if feedback already exists
    if (currentAppointment.student_feedback && currentAppointment.student_feedback.trim() !== "") {
      await connection.rollback();
      connection.release();
      return NextResponse.json(
        { 
          success: false, 
          message: 'Feedback has already been submitted for this session. Feedback cannot be modified.' 
        },
        { status: 400 }
      );
    }

    // 4. Check if session happened at least 1 minute ago (to prevent immediate feedback)
    const [sessionDetails] = await connection.query<RowDataPacket[]>(
      `SELECT session_date, end_time 
       FROM foreign_student_booked_sessions 
       WHERE id = ?`,
      [appointmentId]
    );

    if (sessionDetails.length > 0) {
      const session = sessionDetails[0];
      const now = new Date();
      const sessionDate = new Date(session.session_date);
      const [hours, minutes] = session.end_time.split(':');
      sessionDate.setHours(parseInt(hours), parseInt(minutes), 0, 0);
      
      // Add 1 minute to the end time
      const oneMinuteAfterEnd = new Date(sessionDate.getTime() + 60000);
      
      if (now < oneMinuteAfterEnd) {
        await connection.rollback();
        connection.release();
        return NextResponse.json(
          { 
            success: false, 
            message: 'Feedback can only be submitted 1 minute after the session end time.' 
          },
          { status: 400 }
        );
      }
    }

    // 5. Update appointment with student feedback
    await connection.query(
      `UPDATE foreign_student_booked_sessions 
       SET student_feedback = ?, updated_at = NOW()
       WHERE id = ? AND student_id = ?`,
      [validatedData.feedback, appointmentId, studentId]
    );

    // Commit transaction
    await connection.commit();
    connection.release();

    return NextResponse.json({
      success: true,
      message: 'Feedback submitted successfully'
    }, { status: 200 });

  } catch (err: any) {
    // Rollback on any error
    if (connection) {
      await connection.rollback();
      connection.release();
    }
    
    console.error('Submit feedback error:', err);
    
    // Zod validation errors
    if (err instanceof z.ZodError) {
      const errors = {};
      err.errors.forEach(error => {
        const path = error.path.join('.');
        errors[path] = error.message;
      });
      
      return NextResponse.json(
        { 
          success: false, 
          message: 'Validation failed', 
          errors 
        },
        { status: 400 }
      );
    }
    
    // Database or other errors
    return NextResponse.json(
      { 
        success: false, 
        message: err.message || 'Failed to submit feedback' 
      },
      { status: 500 }
    );
  }
}