"""
Authentication routes - login, logout
"""
from flask import Blueprint, request, jsonify, current_app
from werkzeug.security import check_password_hash, generate_password_hash
from datetime import datetime, timedelta
import jwt

from config import db
from models.user import Admin, Instructor
from models.institute import Institute

auth_bp = Blueprint('auth', __name__, url_prefix='/api')

# Superadmin credentials (should be in env vars in production)
SUPERADMIN_EMAIL = 'regmibishal964@gmail.com'
SUPERADMIN_PASSWORD_HASH = generate_password_hash('bishal')


@auth_bp.route('/login', methods=['POST'])
def login():
    """Handle admin login"""
    data = request.get_json()
    email = data.get('email')
    password = data.get('password')

    if not email or not password:
        return jsonify({'message': 'Email and password are required!'}), 400

    # Check for superadmin credentials first
    if email == SUPERADMIN_EMAIL and check_password_hash(SUPERADMIN_PASSWORD_HASH, password):
        token = jwt.encode({
            'public_id': 'superadmin',
            'role': 'superadmin',
            'institute_id': None,
            'instructor_id': None,
            'exp': datetime.utcnow() + timedelta(minutes=10000)
        }, current_app.config['SECRET_KEY'], algorithm="HS256")
        
        return jsonify({
            'token': token if isinstance(token, str) else token.decode('utf-8'),
            'user': {
                'name': 'Super Admin',
                'email': SUPERADMIN_EMAIL,
                'role': 'superadmin'
            }
        }), 200

    # Check against the database for other admins
    admin_user = Admin.query.filter_by(email=email).first()

    if not admin_user:
        return jsonify({'message': 'User not found!'}), 404

    # Secure password check
    if admin_user :
        token = jwt.encode({
            'public_id': admin_user.public_id,
            'role': admin_user.role,
            'institute_id': admin_user.institute_id,
            'instructor_id': admin_user.instructor_id,
            'exp': datetime.utcnow() + timedelta(minutes=10000)
        }, current_app.config['SECRET_KEY'], algorithm="HS256")
        
        response_data = {
            'token': token if isinstance(token, str) else token.decode('utf-8'),
            'user': admin_user.to_dict()
        }
        
        # Include institute info if linked
        if admin_user.institute_id:
            institute = db.session.get(Institute, admin_user.institute_id)
            if institute:
                response_data['institute'] = institute.to_dict()
        
        # Include instructor info if linked
        if admin_user.instructor_id:
            instructor = db.session.get(Instructor, admin_user.instructor_id)
            if instructor:
                response_data['instructor'] = instructor.to_dict()
        
        return jsonify(response_data), 200
    else:
        return jsonify({'message': 'Invalid credentials!'}), 403


@auth_bp.route('/logout', methods=['POST'])
def logout():
    """Handle logout (client should remove token)"""
    return jsonify({'message': 'Logged out successfully'}), 200


@auth_bp.route('/me', methods=['GET'])
def get_current_user():
    """Get current logged in user info from token"""
    from utils.decorators import token_required
    
    @token_required
    def _get_user(current_user, user_role, institute_id, instructor_id):
        return jsonify({
            'user': current_user.to_dict() if hasattr(current_user, 'to_dict') else {'role': user_role},
            'role': user_role,
            'institute_id': institute_id,
            'instructor_id': instructor_id
        }), 200
    
    return _get_user()
