"""
app/routes/auth.py
==================
Routes autenticazione.

Endpoint:
- POST /api/v1/auth/login         - Login e ottieni token
- POST /api/v1/auth/logout        - Logout (lato client rimuove token)
- POST /api/v1/auth/refresh-token - Refresh JWT token
"""

from flask import Blueprint, request, jsonify, g
from middleware_auth import require_auth

# Crea blueprint per auth routes
auth_bp = Blueprint('auth', __name__, url_prefix='/api/v1/auth')


@auth_bp.route('/login', methods=['POST'])
def login():
    """
    POST /api/v1/auth/login
    
    Login user e ottieni JWT token.
    
    Request body:
    {
        "email": "operatore@studium.it",
        "password": "password123",
        "tenant_id": 1  (opzionale, default 1)
    }
    
    Response success (200):
    {
        "success": true,
        "token": "eyJhbGciOiJIUzI1NiIs...",
        "user": {
            "id": 1,
            "email": "operatore@studium.it",
            "nome": "Operatore Demo",
            "ruolo": "operatore",
            "id_tenant": 1
        },
        "expires_in": 86400
    }
    
    Response error (401):
    {
        "success": false,
        "error": "Invalid password"
    }
    
    Esempio curl:
    curl -X POST http://localhost:5000/api/v1/auth/login \
      -H "Content-Type: application/json" \
      -d '{"email":"demo@studium.it","password":"demo123"}'
    """
    try:
        # Estrai dati da request
        data = request.get_json()
        
        if not data:
            return jsonify({
                'success': False,
                'error': 'Request body is empty'
            }), 400
        
        email = data.get('email', '').strip()
        password = data.get('password', '')
        tenant_id = data.get('tenant_id', 1)
        
        # Validazione input
        if not email or not password:
            return jsonify({
                'success': False,
                'error': 'Email and password are required'
            }), 400
        
        # Usa AuthService (deve essere in g)
        auth_service = g.get('auth_service')
        if not auth_service:
            return jsonify({
                'success': False,
                'error': 'Auth service not initialized'
            }), 500
        
        # Esegui login
        token, user_data, error = auth_service.login(email, password, tenant_id)
        
        if error:
            # Login fallito
            return jsonify({
                'success': False,
                'error': error
            }), 401
        
        # Login riuscito
        return jsonify({
            'success': True,
            'token': token,
            'user': user_data,
            'expires_in': auth_service.jwt_expiration_hours * 3600  # in secondi
        }), 200
    
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'Login error: {str(e)}'
        }), 500


@auth_bp.route('/logout', methods=['POST'])
@require_auth
def logout(tenant_id, user_id, **kwargs):
    """
    POST /api/v1/auth/logout
    
    Logout user. NOTA: il token viene rimosso dal client.
    
    Questo endpoint è più che altro una formalità per log/audit.
    In realtà il logout succede quando client elimina il token
    da localStorage.
    
    Headers richiesti:
    Authorization: Bearer <token>
    
    Response:
    {
        "success": true,
        "message": "Logged out successfully"
    }
    
    Esempio curl:
    curl -X POST http://localhost:5000/api/v1/auth/logout \
      -H "Authorization: Bearer <token>"
    """
    try:
        # Token è valido (è passato @require_auth)
        # Qui potremmo fare log, blacklist del token, etc.
        
        return jsonify({
            'success': True,
            'message': 'Logged out successfully',
            'user_id': user_id,
            'tenant_id': tenant_id
        }), 200
    
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'Logout error: {str(e)}'
        }), 500


@auth_bp.route('/refresh-token', methods=['POST'])
def refresh_token():
    """
    POST /api/v1/auth/refresh-token
    
    Refresh JWT token (ottieni nuovo token senza re-autenticarsi).
    
    Utile quando:
    - Token sta per scadere
    - Client vuole estendere sessione
    - Token è scaduto ma vogliamo dare una chance al client
    
    Request body:
    {
        "token": "eyJhbGciOiJIUzI1NiIs..."
    }
    
    Response success (200):
    {
        "success": true,
        "token": "eyJhbGciOiJIUzI1NiIs...",
        "expires_in": 86400
    }
    
    Response error (401):
    {
        "success": false,
        "error": "Cannot refresh invalid token"
    }
    
    Esempio curl:
    curl -X POST http://localhost:5000/api/v1/auth/refresh-token \
      -H "Content-Type: application/json" \
      -d '{"token":"eyJhbGciOiJIUzI1NiIs..."}'
    """
    try:
        data = request.get_json()
        
        if not data or 'token' not in data:
            return jsonify({
                'success': False,
                'error': 'Token is required'
            }), 400
        
        old_token = data.get('token')
        
        auth_service = g.get('auth_service')
        if not auth_service:
            return jsonify({
                'success': False,
                'error': 'Auth service not initialized'
            }), 500
        
        new_token, error = auth_service.refresh_token(old_token)
        
        if error:
            return jsonify({
                'success': False,
                'error': error
            }), 401
        
        return jsonify({
            'success': True,
            'token': new_token,
            'expires_in': auth_service.jwt_expiration_hours * 3600
        }), 200
    
    except Exception as e:
        return jsonify({
            'success': False,
            'error': f'Token refresh error: {str(e)}'
        }), 500


@auth_bp.route('/me', methods=['GET'])
@require_auth
def get_current_user(tenant_id, user_id, ruolo, **kwargs):
    """
    GET /api/v1/auth/me
    
    Get info del user attualmente loggato.
    
    Richiede autenticazione.
    
    Response:
    {
        "success": true,
        "user": {
            "user_id": 1,
            "email": "operatore@studium.it",
            "tenant_id": 1,
            "ruolo": "operatore"
        }
    }
    
    Esempio curl:
    curl -X GET http://localhost:5000/api/v1/auth/me \
      -H "Authorization: Bearer <token>"
    """
    return jsonify({
        'success': True,
        'user': {
            'user_id': user_id,
            'tenant_id': tenant_id,
            'ruolo': ruolo
        }
    }), 200

