from flask import Blueprint, request, jsonify
from config import db
from models.subscription import SubscriptionType, SubscriptionPlan
from utils.decorators import token_required

subscription_bp = Blueprint('subscription_routes', __name__, url_prefix='/api/admin/subscriptions')

@subscription_bp.route('/types', methods=['GET'])
@token_required
def get_types(current_user, user_role, institute_id, instructor_id):
    types = SubscriptionType.query.order_by(SubscriptionType.display_order.asc()).all()
    return jsonify({
        'success': True,
        'data': [t.to_dict() for t in types]
    }), 200

@subscription_bp.route('/plans', methods=['GET'])
@token_required
def get_plans(current_user, user_role, institute_id, instructor_id):
    plans = SubscriptionPlan.query.order_by(SubscriptionPlan.display_order.asc()).all()
    return jsonify({
        'success': True,
        'data': [p.to_dict() for p in plans]
    }), 200

@subscription_bp.route('/plans', methods=['POST'])
@token_required
def create_plan(current_user, user_role, institute_id, instructor_id):
    data = request.get_json()
    new_plan = SubscriptionPlan(
        subscription_type_id=data.get('subscription_type_id'),
        plan_name=data.get('plan_name'),
        plan_slug=data.get('plan_slug'),
        tier=data.get('tier', 'basic'),
        description=data.get('description'),
        price_monthly_npr=data.get('price_monthly_npr', 0.00),
        price_yearly_npr=data.get('price_yearly_npr'),
        discount_yearly_percent=data.get('discount_yearly_percent', 0.00),
        benefits=data.get('benefits', {}),
        features_list=data.get('features_list', []),
        is_popular=data.get('is_popular', False),
        badge_text=data.get('badge_text'),
        is_active=data.get('is_active', True),
        display_order=data.get('display_order', 0),
        trial_days=data.get('trial_days', 0)
    )
    db.session.add(new_plan)
    db.session.commit()
    return jsonify({'success': True, 'message': 'Plan created successfully'}), 201

@subscription_bp.route('/plans/<int:plan_id>', methods=['PUT'])
@token_required
def update_plan(current_user, user_role, institute_id, instructor_id, plan_id):
    plan = db.session.get(SubscriptionPlan, plan_id)
    if not plan:
        return jsonify({'success': False, 'message': 'Plan not found'}), 404
        
    data = request.get_json()
    allowed_fields = [
        'plan_name', 'plan_slug', 'tier', 'description', 
        'price_monthly_npr', 'price_yearly_npr', 'discount_yearly_percent', 
        'benefits', 'features_list', 'is_popular', 'badge_text', 
        'is_active', 'display_order', 'trial_days'
    ]
                     
    for field in allowed_fields:
        if field in data:
            setattr(plan, field, data[field])
            
    db.session.commit()
    return jsonify({'success': True, 'message': 'Plan updated successfully'}), 200

@subscription_bp.route('/plans/<int:plan_id>', methods=['DELETE'])
@token_required
def delete_plan(current_user, user_role, institute_id, instructor_id, plan_id):
    plan = db.session.get(SubscriptionPlan, plan_id)
    if not plan:
        return jsonify({'success': False, 'message': 'Plan not found'}), 404
        
    db.session.delete(plan)
    db.session.commit()
    return jsonify({'success': True, 'message': 'Plan deleted successfully'}), 200
