import pool from '../../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket } from 'mysql2';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcryptjs';

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

    console.log(body)

    const { email, password } = body;

    // Modified query to join with consultants table to get profile_status
    const [checkEmail] = await pool.query<RowDataPacket[]>(
      `SELECT 
        u.*, 
        c.profile_status
      FROM users u
      LEFT JOIN consultants c ON u.id = c.user_id
      WHERE u.email = ? 
        AND u.is_active = 1 
        AND u.user_type = 'consultant' 
      LIMIT 1`, 
      [email]
    );
    
    if(checkEmail.length === 0) {
      return NextResponse.json(
        { success: false, message: 'Invalid Credentials or You dont have permission to login' },
        { status: 409 }
      );
    }

    const user = checkEmail[0];
    const validPassword = await bcrypt.compare(password, user.password);
    
    if(validPassword)
    {
      const userData = {
        id: user.id,
        name: user.first_name,
        email: user.email,
        role: user.user_type,
        // Include consultant approval status
        consultant_profile: {
          profile_status: user.profile_status || 'incomplete'
        }
      };

      const token = jwt.sign(
        {
          id: user.id,
          name: user.first_name,
          email: user.email,
          role: user.user_type,
          consultant_profile: userData.consultant_profile // Include in JWT if needed
        },
        process.env.JWT_SECRET as string,
        {
          expiresIn: "1d"
        }
      );

      const response = NextResponse.json(
        {
          message: "Login Successfully",
          role: user.user_type,
          data: userData,
          consultant_status: {
            profile_status: user.profile_status,
          }
        },
        {
          status: 200
        }
      );

      response.cookies.set('university-token', token, {httpOnly: true});

      return response;
    }
    else{
      return NextResponse.json(
        {
          message: "Invalid Credentials",
        },
        {
          status: 400
        }
      );
    }

  } catch (err: any) {
    if (err?.issues) {
      // ZodError
      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(
        { ok: false, message: fieldErrors },
        { status: 400 }
      );
    }

    console.error("Login API error:", err);
    return NextResponse.json(
      { ok: false, message: "Internal server error" },
      { status: 500 }
    );
  }
}