"""
Router para manejo de favoritos/wishlist.
"""
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.db import get_db_connection
from app.auth import get_current_user
from app.utils.validators import validate_id_format, validate_pagination_params
from app.utils.serializers import favorite_to_dict, tire_to_dict
from app.utils.logger import get_logger
from datetime import datetime, timezone
import uuid

favorites_bp = Blueprint('favorites', __name__)
logger = get_logger(__name__)


@favorites_bp.route('', methods=['GET'])
@jwt_required()
def get_favorites():
    """Get all favorites for the current user."""
    user = get_current_user()
    if not user:
        return jsonify({'error': 'Authentication required'}), 401
    
    skip = request.args.get('skip', 0, type=int)
    limit = request.args.get('limit', 50, type=int)
    
    # Validar paginación
    valid, skip_val, limit_val, error_msg = validate_pagination_params(skip, limit, max_limit=100)
    if not valid:
        return jsonify({'error': error_msg}), 400
    
    conn = get_db_connection()
    if not conn:
        return jsonify({'error': 'Database connection error'}), 500
    
    try:
        cursor = conn.cursor()
        user_id = user.get('id')
        
        # Obtener favoritos con información de llantas
        cursor.execute("""
            SELECT f.id, f.usuario_id, f.llanta_id, f.creado_en,
                   t.marca, t.modelo, t.ancho, t.relacion_aspecto, t.diametro, 
                   t.tipo, t.url_imagen
            FROM favoritos f
            INNER JOIN llantas t ON f.llanta_id = t.id
            WHERE f.usuario_id = %s
            ORDER BY f.creado_en DESC
            LIMIT %s OFFSET %s
        """, (user_id, limit_val, skip_val))
        
        favorites_data = cursor.fetchall()
        
        # Contar total
        cursor.execute("SELECT COUNT(*) as total FROM favoritos WHERE usuario_id = %s", (user_id,))
        total_result = cursor.fetchone()
        total_count = total_result['total'] if total_result else 0
        
        cursor.close()
        conn.close()
        
        # Construir respuesta con información de llanta
        favorites_list = []
        for fav in favorites_data:
            favorite_dict = favorite_to_dict(fav)
            # Agregar información de la llanta
            tire_info = {
                'id': fav.get('llanta_id'),
                'brand': fav.get('marca'),
                'model': fav.get('modelo'),
                'size': {
                    'width': fav.get('ancho'),
                    'aspectRatio': fav.get('relacion_aspecto'),
                    'diameter': fav.get('diametro')
                },
                'type': fav.get('tipo'),
                'imageUrl': fav.get('url_imagen')
            }
            favorite_dict['tire'] = tire_info
            favorites_list.append(favorite_dict)
        
        return jsonify({
            'favorites': favorites_list,
            'pagination': {
                'skip': skip_val,
                'limit': limit_val,
                'total': total_count,
                'has_more': (skip_val + limit_val) < total_count
            }
        }), 200
    
    except Exception as e:
        if 'cursor' in locals():
            cursor.close()
        if conn:
            conn.close()
        logger.error(f"Error in get_favorites: {str(e)}", exc_info=True, extra={
            'endpoint': 'get_favorites',
            'user_id': user.get('id') if user else None
        })
        return jsonify({'error': 'Error retrieving favorites'}), 500


@favorites_bp.route('', methods=['POST'])
@jwt_required()
def add_favorite():
    """Add a tire to favorites."""
    user = get_current_user()
    if not user:
        return jsonify({'error': 'Authentication required'}), 401
    
    data = request.get_json()
    if not data:
        return jsonify({'error': 'Request body is required'}), 400
    
    tire_id = data.get('tire_id')
    if not tire_id:
        return jsonify({'error': 'tire_id is required'}), 400
    
    # Validar formato de ID
    if not validate_id_format(tire_id):
        return jsonify({'error': 'Invalid tire_id format'}), 400
    
    conn = get_db_connection()
    if not conn:
        return jsonify({'error': 'Database connection error'}), 500
    
    try:
        cursor = conn.cursor()
        user_id = user.get('id')
        
        # Verificar que la llanta existe
        cursor.execute("SELECT id FROM llantas WHERE id = %s", (tire_id,))
        if not cursor.fetchone():
            cursor.close()
            conn.close()
            return jsonify({'error': 'Tire not found'}), 404
        
        # Verificar si ya está en favoritos
        cursor.execute("""
            SELECT id FROM favoritos 
            WHERE usuario_id = %s AND llanta_id = %s
        """, (user_id, tire_id))
        if cursor.fetchone():
            cursor.close()
            conn.close()
            return jsonify({'error': 'Tire already in favorites'}), 400
        
        # Crear favorito
        favorite_id = f"fav-{user_id}-{tire_id}-{uuid.uuid4().hex[:8]}"
        cursor.execute("""
            INSERT INTO favoritos (id, usuario_id, llanta_id, creado_en)
            VALUES (%s, %s, %s, %s)
        """, (favorite_id, user_id, tire_id, datetime.now(timezone.utc)))
        
        conn.commit()
        
        # Log change for audit
        from app.governance.audit import log_change
        log_change(
            table='favoritos',
            record_id=favorite_id,
            action='INSERT',
            user_id=user_id,
            user_email=user.get('correo'),
            new_data={'usuario_id': user_id, 'llanta_id': tire_id}
        )
        
        # Obtener favorito creado
        cursor.execute("""
            SELECT id, usuario_id, llanta_id, creado_en
            FROM favoritos WHERE id = %s
        """, (favorite_id,))
        favorite_data = cursor.fetchone()
        
        cursor.close()
        conn.close()
        
        return jsonify(favorite_to_dict(favorite_data)), 201
    
    except Exception as e:
        if conn:
            conn.rollback()
            if 'cursor' in locals():
                cursor.close()
            conn.close()
        logger.error(f"Error in add_favorite: {str(e)}", exc_info=True, extra={
            'endpoint': 'add_favorite',
            'user_id': user.get('id') if user else None,
            'tire_id': tire_id
        })
        return jsonify({'error': 'Error adding favorite'}), 500


@favorites_bp.route('/<favorite_id>', methods=['DELETE'])
@jwt_required()
def remove_favorite(favorite_id):
    """Remove a tire from favorites."""
    user = get_current_user()
    if not user:
        return jsonify({'error': 'Authentication required'}), 401
    
    conn = get_db_connection()
    if not conn:
        return jsonify({'error': 'Database connection error'}), 500
    
    try:
        cursor = conn.cursor()
        user_id = user.get('id')
        
        # Verificar que el favorito existe y pertenece al usuario
        cursor.execute("""
            SELECT id, llanta_id FROM favoritos
            WHERE id = %s AND usuario_id = %s
        """, (favorite_id, user_id))
        favorite_data = cursor.fetchone()
        
        if not favorite_data:
            cursor.close()
            conn.close()
            return jsonify({'error': 'Favorite not found'}), 404
        
        # Eliminar favorito
        cursor.execute("DELETE FROM favoritos WHERE id = %s", (favorite_id,))
        conn.commit()
        
        # Log change for audit
        from app.governance.audit import log_change
        log_change(
            table='favoritos',
            record_id=favorite_id,
            action='DELETE',
            user_id=user_id,
            user_email=user.get('correo'),
            old_data={'usuario_id': user_id, 'llanta_id': favorite_data.get('llanta_id')}
        )
        
        cursor.close()
        conn.close()
        
        return '', 204
    
    except Exception as e:
        if conn:
            conn.rollback()
            if 'cursor' in locals():
                cursor.close()
            conn.close()
        logger.error(f"Error in remove_favorite: {str(e)}", exc_info=True, extra={
            'endpoint': 'remove_favorite',
            'user_id': user.get('id') if user else None,
            'favorite_id': favorite_id
        })
        return jsonify({'error': 'Error removing favorite'}), 500


@favorites_bp.route('/tire/<tire_id>', methods=['DELETE'])
@jwt_required()
def remove_favorite_by_tire(tire_id):
    """Remove a tire from favorites by tire_id."""
    user = get_current_user()
    if not user:
        return jsonify({'error': 'Authentication required'}), 401
    
    conn = get_db_connection()
    if not conn:
        return jsonify({'error': 'Database connection error'}), 500
    
    try:
        cursor = conn.cursor()
        user_id = user.get('id')
        
        # Verificar que el favorito existe
        cursor.execute("""
            SELECT id FROM favoritos
            WHERE usuario_id = %s AND llanta_id = %s
        """, (user_id, tire_id))
        favorite_data = cursor.fetchone()
        
        if not favorite_data:
            cursor.close()
            conn.close()
            return jsonify({'error': 'Favorite not found'}), 404
        
        favorite_id = favorite_data['id']
        
        # Eliminar favorito
        cursor.execute("DELETE FROM favoritos WHERE id = %s", (favorite_id,))
        conn.commit()
        
        # Log change for audit
        from app.governance.audit import log_change
        log_change(
            table='favoritos',
            record_id=favorite_id,
            action='DELETE',
            user_id=user_id,
            user_email=user.get('correo'),
            old_data={'usuario_id': user_id, 'llanta_id': tire_id}
        )
        
        cursor.close()
        conn.close()
        
        return '', 204
    
    except Exception as e:
        if conn:
            conn.rollback()
            if 'cursor' in locals():
                cursor.close()
            conn.close()
        logger.error(f"Error in remove_favorite_by_tire: {str(e)}", exc_info=True, extra={
            'endpoint': 'remove_favorite_by_tire',
            'user_id': user.get('id') if user else None,
            'tire_id': tire_id
        })
        return jsonify({'error': 'Error removing favorite'}), 500


@favorites_bp.route('/check/<tire_id>', methods=['GET'])
@jwt_required()
def check_favorite(tire_id):
    """Check if a tire is in user's favorites."""
    user = get_current_user()
    if not user:
        return jsonify({'error': 'Authentication required'}), 401
    
    conn = get_db_connection()
    if not conn:
        return jsonify({'error': 'Database connection error'}), 500
    
    try:
        cursor = conn.cursor()
        user_id = user.get('id')
        
        cursor.execute("""
            SELECT id FROM favoritos
            WHERE usuario_id = %s AND llanta_id = %s
        """, (user_id, tire_id))
        
        is_favorite = cursor.fetchone() is not None
        
        cursor.close()
        conn.close()
        
        return jsonify({'is_favorite': is_favorite}), 200
    
    except Exception as e:
        if 'cursor' in locals():
            cursor.close()
        if conn:
            conn.close()
        logger.error(f"Error in check_favorite: {str(e)}", exc_info=True, extra={
            'endpoint': 'check_favorite',
            'user_id': user.get('id') if user else None,
            'tire_id': tire_id
        })
        return jsonify({'error': 'Error checking favorite'}), 500
