from flask import Blueprint, render_template
from flask_login import current_user
from sqlalchemy import func

from app.auth.access import roles_required
from app.models import ActivityRegistration, Donation, HeartTransaction
from app.models.enums import DonationStatus, RegistrationStatus

bp = Blueprint("impact", __name__, url_prefix="/impact")
EMPLOYEE_PORTAL_ROLES = ("EMPLOYEE", "MANAGER", "SUPER_ADMIN", "PIRAMAL_ADMIN", "INDIAISUS_ADMIN")


@bp.route("/")
@roles_required(*EMPLOYEE_PORTAL_ROLES)
def dashboard():
    employee = current_user.employee
    volunteer_hours = completed = donation_total = hearts = 0
    heart_ledger = []
    if employee:
        volunteer_hours = float(ActivityRegistration.query.with_entities(func.coalesce(func.sum(ActivityRegistration.volunteer_hours), 0)).filter_by(employee_id=employee.id).scalar() or 0)
        completed = ActivityRegistration.query.filter_by(employee_id=employee.id, status=RegistrationStatus.COMPLETED).count()
        donation_total = float(Donation.query.with_entities(func.coalesce(func.sum(Donation.amount), 0)).filter_by(employee_id=employee.id, status=DonationStatus.SUCCESSFUL).scalar() or 0)
        hearts = int(HeartTransaction.query.with_entities(func.coalesce(func.sum(HeartTransaction.hearts), 0)).filter_by(employee_id=employee.id).scalar() or 0)
        heart_ledger = HeartTransaction.query.filter_by(employee_id=employee.id).order_by(HeartTransaction.created_at.desc()).limit(20).all()
    return render_template("impact/dashboard.html", volunteer_hours=volunteer_hours, completed=completed, donation_total=donation_total, hearts=hearts, heart_ledger=heart_ledger)
