// app/api/frontend/login-foreign-student/route.js
import pool from '../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket } from 'mysql2';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();

    console.log('Foreign student login attempt:', { email: body.email });

    const { email, password } = body;

    // Check if foreign student exists and is active
    const [checkEmail] = await pool.query<RowDataPacket[]>(
      `SELECT * FROM foreign_students 
       WHERE email = ? 
       AND is_active = 1 
       LIMIT 1`, 
      [email]
    );
    
    if (checkEmail.length === 0) {
      return NextResponse.json(
        { 
          success: false, 
          message: 'Invalid credentials or account not found' 
        },
        { status: 401 }
      );
    }

    // Verify password
    const validPassword = await bcrypt.compare(password, checkEmail[0].password_hash);
    
    if (!validPassword) {
      return NextResponse.json(
        {
          message: "Invalid Credentials",
        },
        {
          status: 400
        }
      );
    }

    // Prepare user data for response
    const userData = {
      id: checkEmail[0].id,
      name: checkEmail[0].name,
      email: checkEmail[0].email,
      role: 'foreign-student',
    };

    // Create JWT token
    const token = jwt.sign(
      {
        id: checkEmail[0].id,
        name: checkEmail[0].name,
        email: checkEmail[0].email,
        role: 'foreign-student'
      },
      process.env.JWT_SECRET as string,
      {
        expiresIn: "1d"
      }
    );

    // Update last login time
    await pool.query(
      'UPDATE foreign_students SET updated_at = NOW(), updated_at = NOW() WHERE id = ?',
      [checkEmail[0].id]
    );

    // Create response with cookie
    const response = NextResponse.json(
      {
        message: "Login Successful",
        role: 'foreign-student',
        data: userData
      },
      {
        status: 200
      }
    );

    // Set HTTP-only cookie
    response.cookies.set('university-token', token, {
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'strict',
      path: '/',
      maxAge: 24 * 60 * 60 // 1 day
    });

    return response;

  } catch (err: any) {
    console.error("Foreign student login POST error:", err);
    
    // Handle specific errors
    if (err.code === 'ECONNREFUSED') {
      return NextResponse.json(
        { 
          success: false, 
          message: "Database connection failed" 
        },
        { status: 503 }
      );
    }

    return NextResponse.json(
      { 
        success: false, 
        message: "Internal server error" 
      },
      { status: 500 }
    );
  }
}