from flask import jsonify
from flask_login import login_required
from . import admin_bp
from ...models.rate import Rate
from .routes import admin_or_comercial_required
from sqlalchemy import distinct

@admin_bp.route('/api/tarifas/comercializadoras', methods=['GET'])
@login_required
@admin_or_comercial_required
def get_suppliers():
    """Devuelve la lista de comercializadoras disponibles para autocomplete"""
    try:
        # Obtener lista distinta de comercializadoras que no sean nulas
        suppliers = [r[0] for r in Rate.query.with_entities(distinct(Rate.supplier))
                    .filter(Rate.supplier.isnot(None))
                    .order_by(Rate.supplier).all()]
        
        return jsonify({'success': True, 'suppliers': suppliers})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500

@admin_bp.route('/api/tarifas/tipos', methods=['GET'])
@login_required
@admin_or_comercial_required
def get_tariff_types():
    """Devuelve la lista de tipos de tarifas disponibles para autocomplete"""
    try:
        # Obtener lista distinta de tipos de tarifas que no sean nulos
        tariff_types = [r[0] for r in Rate.query.with_entities(distinct(Rate.tariff_type))
                      .filter(Rate.tariff_type.isnot(None))
                      .order_by(Rate.tariff_type).all()]
        
        return jsonify({'success': True, 'tariff_types': tariff_types})
    except Exception as e:
        return jsonify({'success': False, 'message': str(e)}), 500
