from flask import Blueprint, request, jsonify
from config import db
from models.content import HomeSlider
from utils.decorators import token_required

slider_bp = Blueprint('slider_routes', __name__, url_prefix='/api/admin/sliders')

@slider_bp.route('', methods=['GET'])
@token_required
def get_sliders(current_user, user_role, institute_id, instructor_id):
    """Get all home sliders"""
    sliders = HomeSlider.query.order_by(HomeSlider.display_order.asc()).all()
    return jsonify({
        'success': True,
        'data': [s.to_dict() for s in sliders]
    }), 200

@slider_bp.route('', methods=['POST'])
@token_required
def create_slider(current_user, user_role, institute_id, instructor_id):
    """Create a new slider"""
    data = request.get_json()
    new_slider = HomeSlider(
        title=data.get('title'),
        description=data.get('description'),
        image_url=data.get('image_url'),
        link_type=data.get('link_type', 'internal'),
        link_value=data.get('link_value'),
        display_order=data.get('display_order', 0),
        is_active=data.get('is_active', True),
        button_text=data.get('button_text', 'Learn More'),
        background_color=data.get('background_color', '#6366f1')
    )
    db.session.add(new_slider)
    db.session.commit()
    return jsonify({'success': True, 'message': 'Slider created successfully'}), 201

@slider_bp.route('/<int:slider_id>', methods=['PUT'])
@token_required
def update_slider(current_user, user_role, institute_id, instructor_id, slider_id):
    """Update a slider"""
    slider = db.session.get(HomeSlider, slider_id)
    if not slider:
        return jsonify({'success': False, 'message': 'Slider not found'}), 404
        
    data = request.get_json()
    allowed_fields = ['title', 'description', 'image_url', 'link_type', 'link_value', 
                     'display_order', 'is_active', 'button_text', 'background_color']
                     
    for field in allowed_fields:
        if field in data:
            setattr(slider, field, data[field])
            
    db.session.commit()
    return jsonify({'success': True, 'message': 'Slider updated successfully'}), 200

@slider_bp.route('/<int:slider_id>', methods=['DELETE'])
@token_required
def delete_slider(current_user, user_role, institute_id, instructor_id, slider_id):
    """Delete a slider"""
    slider = db.session.get(HomeSlider, slider_id)
    if not slider:
        return jsonify({'success': False, 'message': 'Slider not found'}), 404
        
    db.session.delete(slider)
    db.session.commit()
    return jsonify({'success': True, 'message': 'Slider deleted successfully'}), 200
