from flask import Blueprint, jsonify
from db.model import User, Course, db
from sqlalchemy import select, func

public_summary = Blueprint('public', __name__)

@public_summary.route('/stats/total-users', methods=['GET'])
def get_total_users():
    """
    Fetch total user count.
    """
    try:
        total_users = db.session.execute(
            select(func.count()).select_from(User)
        ).scalar()

        return jsonify({'totalUsers': total_users}), 200

    except Exception as e:
        return jsonify({'message': f'An error occurred: {str(e)}'}), 500


@public_summary.route('/stats/total-authors', methods=['GET'])
def get_total_authors():
    """
    Fetch total authors (users who have created courses).
    """
    try:
        total_authors = db.session.execute(
            select(func.count(func.distinct(Course.authorID)))
            .select_from(Course)
        ).scalar()

        return jsonify({'totalAuthors': total_authors}), 200

    except Exception as e:
        return jsonify({'message': f'An error occurred: {str(e)}'}), 500


@public_summary.route('/stats/total-courses', methods=['GET'])
def get_total_courses():
    """
    Fetch total course count.
    """
    try:
        total_courses = db.session.execute(
            select(func.count()).select_from(Course)
        ).scalar()

        return jsonify({'totalCourses': total_courses}), 200

    except Exception as e:
        return jsonify({'message': f'An error occurred: {str(e)}'}), 500


@public_summary.route('/stats/subscribed-users', methods=['GET'])
def get_subscribed_users():
    """
    Fetch count of users subscribed to the newsletter and are activated.
    """
    try:
        subscribed_users = db.session.execute(
            select(func.count(User.email))
            .select_from(User)
            .where(User.isActivated == True)
        ).scalar()

        return jsonify({'subscribedNewsletter': subscribed_users}), 200

    except Exception as e:
        return jsonify({'message': f'An error occurred: {str(e)}'}), 500