from flask import Blueprint, render_template, request
from flask_login import login_required
from decorators import roles_required
from models import db, Invoice
from sqlalchemy import func

reports_bp = Blueprint("reports", __name__, url_prefix="/reports")


@reports_bp.route("/profit", methods=["GET"])
@login_required
@roles_required("Admin", "Accounts")
def profit_report():
    year = int(request.args.get("year") or 0)

    q = db.session.query(
        Invoice.invoice_year.label("y"),
        Invoice.invoice_month.label("m"),
        func.sum(Invoice.amount).label("total_amount"),
        func.sum(Invoice.vendor_payment).label("total_vendor"),
        func.sum(Invoice.gst_amount).label("total_gst"),
        func.sum(Invoice.profit_margin).label("total_profit"),
        func.count(Invoice.id).label("count_invoices"),
    )

    if year:
        q = q.filter(Invoice.invoice_year == year)

    q = q.group_by(Invoice.invoice_year, Invoice.invoice_month).order_by(Invoice.invoice_year.desc(), Invoice.invoice_month.desc())

    rows = q.all()
    years = [r[0] for r in db.session.query(Invoice.invoice_year).distinct().order_by(Invoice.invoice_year.desc()).all()]

    return render_template("profit_report.html", rows=rows, year=year, years=years)


@reports_bp.route("/vendor", methods=["GET"])
@login_required
@roles_required("Admin", "Accounts")
def vendor_report():
    year = int(request.args.get("year") or 0)

    q = db.session.query(
        Invoice.invoice_year.label("y"),
        Invoice.invoice_month.label("m"),
        func.sum(Invoice.vendor_payment).label("vendor_payable"),
        func.sum(Invoice.amount).label("customer_billed"),
        func.sum(Invoice.profit_margin).label("profit"),
        func.count(Invoice.id).label("count_invoices"),
    )

    if year:
        q = q.filter(Invoice.invoice_year == year)

    q = q.group_by(Invoice.invoice_year, Invoice.invoice_month).order_by(Invoice.invoice_year.desc(), Invoice.invoice_month.desc())

    rows = q.all()
    years = [r[0] for r in db.session.query(Invoice.invoice_year).distinct().order_by(Invoice.invoice_year.desc()).all()]

    return render_template("vendor_report.html", rows=rows, year=year, years=years)