"""
Authentication related routes
"""
from flask import Blueprint, jsonify, request, make_response
from utils import require_api_key, add_keep_alive, format_api_response, create_error_response
from login import goog_login, login
from reset_pass import reset_pass
from signup import signup_user
from report import report_issue


auth_bp = Blueprint('auth', __name__)


@auth_bp.route('/login', methods=['POST', 'GET'])
@require_api_key
def logon():
    response = make_response(login(request))
    return add_keep_alive(response)


@auth_bp.route('/reset-pass', methods=['POST', 'GET'])
@auth_bp.route('/reset_password', methods=['POST', 'GET'])  # Add alias for frontend compatibility
@require_api_key
def resetpass():
    response = make_response(reset_pass(request))
    return add_keep_alive(response)


@auth_bp.route('/google_login', methods=['POST', 'GET'])
@require_api_key
def google_logon():
    response = make_response(goog_login(request))
    return add_keep_alive(response)


@auth_bp.route('/signup', methods=['POST', 'GET'])
@require_api_key
def signup():
    response = make_response(signup_user(request))
    return add_keep_alive(response)


@auth_bp.route('/report', methods=['POST', 'GET'])
@require_api_key
def repor():
    response = make_response(report_issue(request))
    return add_keep_alive(response)


@auth_bp.route('/auth/refresh', methods=['POST'])
@require_api_key
def refresh_token():
    """Refresh JWT access token using refresh token"""
    try:
        from auth.jwt_manager import JWTManager
        import jwt
        
        data = request.get_json()
        if not data or 'refresh_token' not in data:
            return create_error_response(
                "Refresh token required",
                status_code=400,
                error_code="VALIDATION_ERROR"
            )
        
        refresh_token = data['refresh_token']
        
        try:
            # Verify refresh token
            payload = JWTManager.verify_token(refresh_token, 'refresh')
            user_id = payload['user_id']
            
            # Get user email from database to generate new tokens
            from database import get_cached_connection
            conn = get_cached_connection()
            cursor = conn.cursor(dictionary=True)
            
            cursor.execute("SELECT email FROM `user` WHERE id = %s", (user_id,))
            user = cursor.fetchone()
            cursor.close()
            conn.close()
            
            if not user:
                return create_error_response(
                    "User not found",
                    status_code=404,
                    error_code="USER_NOT_FOUND"
                )
            
            # Generate new tokens
            new_access_token, new_refresh_token = JWTManager.generate_tokens(user_id, user['email'])
            
            return jsonify(format_api_response(
                data={
                    "access_token": new_access_token,
                    "refresh_token": new_refresh_token
                },
                message="Token refreshed successfully",
                include_legacy_fields={
                    "response": "success",
                    "access_token": new_access_token,
                    "refresh_token": new_refresh_token
                }
            ))
            
        except jwt.InvalidTokenError:
            return create_error_response(
                "Invalid refresh token",
                status_code=401,
                error_code="INVALID_TOKEN"
            )
            
    except Exception as e:
        import logging
        logger = logging.getLogger(__name__)
        logger.error(f"Token refresh error: {str(e)}")
        return create_error_response(
            "Token refresh failed",
            status_code=500,
            error_code="TOKEN_REFRESH_ERROR"
        )


@auth_bp.route('/auth/logout', methods=['POST'])
@require_api_key
def logout():
    """Logout user - in future can blacklist tokens"""
    try:
        from auth.jwt_manager import JWTManager
        
        auth_header = request.headers.get('Authorization')
        if auth_header and auth_header.startswith('Bearer '):
            token = auth_header.split(' ')[1]
            try:
                payload = JWTManager.verify_token(token)
                user_id = payload['user_id']
                
                # Update logged_in status in database
                from database import get_cached_connection
                conn = get_cached_connection()
                cursor = conn.cursor()
                
                cursor.execute("UPDATE `user` SET `logged_in`='0' WHERE id = %s", (user_id,))
                conn.commit()
                cursor.close()
                conn.close()
                
            except:
                pass  # Token invalid, but logout should still succeed
        
        return jsonify(format_api_response(
            data={"logged_out": True},
            message="Logged out successfully",
            include_legacy_fields={"response": "success", "message": "Logged out successfully"}
        ))
        
    except Exception as e:
        import logging
        logger = logging.getLogger(__name__)
        logger.error(f"Logout error: {str(e)}")
        return jsonify(format_api_response(
            data={"logged_out": True},
            message="Logged out",
            include_legacy_fields={"response": "success", "message": "Logged out"}
        ))  # Always succeed for logout