// app/api/appapis/login/route.ts (Updated to handle both student and consultant)
import pool from '../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket } from 'mysql2';
import { loginSchema as Schema } from '../../../../validations/LoginValidation';
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 commingHeaders = 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 && commingHeaders !== process.env.APP_API_KEY) {
      return NextResponse.json(
        { success: false, message: 'Unauthorized Access' },
        { status: 401, headers: corsHeaders }
      );
    }

    const parsed = Schema.parse(body);
    const { email, password } = parsed;
    const { user_type } = body; // 'student' or 'consultant' from mobile app
    
    // Build query based on user type
    let userQuery = `
      SELECT 
        u.*, 
        c.profile_status,
        c.company_name,
        c.availability,
        c.specialization
      FROM users u
      LEFT JOIN consultants c ON u.id = c.user_id
      WHERE u.email = ? 
        AND u.is_active = 1 
    `;
    
    if (user_type === 'consultant') {
      userQuery += ` AND u.user_type IN ('consultant', 'admin')`;
    } else if (user_type === 'student') {
      userQuery += ` AND u.user_type = 'student'`;
    } else {
      // If no user_type specified, check both
      userQuery += ` AND u.user_type IN ('student', 'consultant')`;
    }
    
    userQuery += ` LIMIT 1`;
    
    const [checkEmail] = await pool.query<RowDataPacket[]>(userQuery, [email]);

    if (checkEmail.length === 0) {
      return NextResponse.json(
        { 
          success: false, 
          message: user_type 
            ? `Invalid Credentials or No ${user_type} account found` 
            : 'Invalid Credentials' 
        },
        { status: 409, headers: corsHeaders }
      );
    }

    const validPassword = await bcrypt.compare(password, checkEmail[0].password);
    if (validPassword) {
      const userData = {
        id: checkEmail[0].id,
        first_name: checkEmail[0].first_name,
        last_name: checkEmail[0].last_name,
        avatar: checkEmail[0].image,
        email: checkEmail[0].email,
        role: checkEmail[0].user_type,
        ...(checkEmail[0].profile_status && {
          consultant_profile: {
            profile_status: checkEmail[0].profile_status,
            company_name: checkEmail[0].company_name,
            experience: checkEmail[0].availability,
            specialization: checkEmail[0].specialization
          }
        })
      };

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

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

      const response = NextResponse.json(
        {
          success: true,
          message: "Login Successfully",
          role: checkEmail[0].user_type,
          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('app-token', accessToken, { 
          httpOnly: true,
          secure: process.env.NODE_ENV === 'production',
          sameSite: 'lax',
          maxAge: 7 * 24 * 60 * 60
        });
        
        response.cookies.set('app-refresh-token', refreshToken, { 
          httpOnly: true,
          secure: process.env.NODE_ENV === 'production',
          sameSite: 'lax',
          maxAge: 7 * 24 * 60 * 60
        });
      }

      return response;
    } else {
      return NextResponse.json(
        {
          success: false,
          message: "Invalid Credentials",
        },
        {
          status: 401,
          headers: corsHeaders
        }
      );
    }
  } catch (err: any) {
    if (err?.issues) {
      const fieldErrors: Record<string, string[]> = {};
      for (const issue of err.issues) {
        const key = (issue.path?.[0] as string) ?? '_';
        fieldErrors[key] = fieldErrors[key] || [];
        fieldErrors[key].push(issue.message);
      }
      return NextResponse.json(
        { success: false, message: fieldErrors },
        { status: 400, headers: corsHeaders }
      );
    }

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