// app/api/appapis/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';

const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization, x-api-key',
  'Access-Control-Allow-Credentials': 'true',
};

export async function OPTIONS() {
  return new NextResponse(null, {
    status: 204,
    headers: corsHeaders,
  });
}

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const incomingHeaders = req.headers.get("authorization");
    const userAgent = req.headers.get("user-agent") || "";
    const isMobileApp = userAgent.includes("Expo") || userAgent.includes("ReactNative");

    // For mobile app, we check for API key
    if (isMobileApp && incomingHeaders !== process.env.APP_API_KEY) {
      return NextResponse.json(
        { success: false, message: 'Unauthorized Access' },
        { status: 401, headers: corsHeaders }
      );
    }

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

    const { email, password } = body;

    // Validation
    if (!email || !password) {
      return NextResponse.json(
        { 
          success: false, 
          message: "Email and password are required" 
        },
        { status: 400, headers: corsHeaders }
      );
    }

    // 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, headers: corsHeaders }
      );
    }

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

    // Prepare user data for response (matching student response structure)
    const userData = {
      id: checkEmail[0].id,
      first_name: checkEmail[0].first_name || checkEmail[0].name?.split(' ')[0] || '',
      last_name: checkEmail[0].last_name || checkEmail[0].name?.split(' ')[1] || '',
      avatar: checkEmail[0].avatar || checkEmail[0].profile_image || null,
      email: checkEmail[0].email,
      role: 'foreign-student',
      country: checkEmail[0].country || null,
      university: checkEmail[0].university || null,
      program: checkEmail[0].program || null,
    };

    // Generate ACCESS token
    const accessToken = jwt.sign(
      {
        id: checkEmail[0].id,
        first_name: userData.first_name,
        last_name: userData.last_name,
        avatar: userData.avatar,
        email: checkEmail[0].email,
        role: 'foreign-student',
        user_type: 'foreign-student',
        type: 'access'
      },
      process.env.JWT_SECRET as string,
      { expiresIn: "7d" }
    );

    // Generate REFRESH token
    const refreshToken = jwt.sign(
      {
        id: checkEmail[0].id,
        type: 'refresh',
        role: 'foreign-student'
      },
      process.env.JWT_REFRESH_SECRET as string,
      { expiresIn: "7d" }
    );

    // Create response with consistent structure
    const response = NextResponse.json(
      {
        success: true,
        message: "Login Successfully",
        role: 'foreign-student',
        data: userData,
        token: accessToken,
        refreshToken: refreshToken
      },
      {
        status: 200,
        headers: corsHeaders
      }
    );

    // Set cookies only for web, mobile app will handle tokens in response body
    if (!isMobileApp) {
      response.cookies.set('university-token', accessToken, { 
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        path: '/',
        maxAge: 7 * 24 * 60 * 60 // 7 days
      });
      
      response.cookies.set('university-refresh-token', refreshToken, { 
        httpOnly: true,
        secure: process.env.NODE_ENV === 'production',
        sameSite: 'lax',
        path: '/',
        maxAge: 7 * 24 * 60 * 60 // 7 days
      });
    }

    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, headers: corsHeaders }
      );
    }

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