# ============================================================
# Summary / Meta / Settings (Admin / HR)     /api/timesheet/summary|meta|settings/
# ============================================================
from decimal import Decimal

from django.db.models import Count, Sum
from django.utils import timezone
from rest_framework.views import APIView

from Employee.models import Department

from .common import (OvertimeClaim, TimesheetAuthMixin, TimesheetEntry, TimesheetProject, TimesheetSetting, err, get_setting, inr, iso, ok,
                     parse_month_year, to_bool, to_decimal, to_int, MODULE)


def setting_row(s):
    return {"standard_daily_hours": float(s.standard_daily_hours), "max_daily_hours": float(s.max_daily_hours), "auto_overtime": s.auto_overtime,
            "overtime_multiplier": float(s.overtime_multiplier), "week_start_day": s.week_start_day, "backdate_limit_days": s.backdate_limit_days,
            "enforce_allocation": s.enforce_allocation}


class SummaryView(TimesheetAuthMixin, APIView):
    """GET /api/timesheet/summary/?month=&year="""
    permission_action = "view"

    def get(self, request):
        co = self.company()
        try:
            month, year = parse_month_year(request.query_params)
        except ValueError as ex:
            return err("VALIDATION", str(ex))
        e = TimesheetEntry.objects.filter(company=co, is_active=True, work_date__month=month, work_date__year=year)
        live = e.filter(status__in=["Submitted", "Approved"])
        agg = live.aggregate(h=Sum("hours"), ot=Sum("overtime_hours"))
        claims = OvertimeClaim.objects.filter(company=co, is_active=True, month=month, year=year)
        ready = claims.filter(status="Approved").aggregate(p=Sum("calculated_pay"))["p"] or Decimal("0")
        return ok("TIMESHEET_SUMMARY", "Timesheet summary.", {
            "month": month, "year": year,
            "total_hours": float(agg["h"] or 0), "overtime_hours": float(agg["ot"] or 0),
            "entries_by_status": {s: e.filter(status=s).count() for s, _ in TimesheetEntry.STATUS},
            "pending_approvals": TimesheetEntry.objects.filter(company=co, is_active=True, status="Submitted").count(),
            "active_projects": TimesheetProject.objects.filter(company=co, is_active=True, status="Active").count(),
            "overtime_claims_pending": claims.filter(status="Pending").count(),
            "overtime_ready_for_payroll": float(ready), "overtime_ready_for_payroll_label": inr(ready)})


class MetaView(TimesheetAuthMixin, APIView):
    """GET /api/timesheet/meta/   dropdown data for every Timesheet form"""
    permission_action = "view"

    def get(self, request):
        co = self.company()
        return ok("TIMESHEET_META", "Timesheet dropdowns.", {
            "tabs": ["timesheets", "project-allocation", "overtime-claims", "timesheet-approval"],
            "entry_statuses": [k for k, _ in TimesheetEntry.STATUS], "project_statuses": [k for k, _ in TimesheetProject.STATUS],
            "claim_statuses": [k for k, _ in OvertimeClaim.STATUS],
            "projects": list(TimesheetProject.objects.filter(company=co, is_active=True).values("id", "code", "title", "status")),
            "departments": list(Department.objects.filter(company=co, is_active=True).values("id", "name")),
            "settings": setting_row(get_setting(co))})


class SettingsView(TimesheetAuthMixin, APIView):
    """GET/PUT/PATCH /api/timesheet/settings/   {standard_daily_hours, max_daily_hours, auto_overtime, overtime_multiplier, week_start_day, backdate_limit_days, enforce_allocation}"""

    def get(self, request):
        return ok("TIMESHEET_SETTINGS", "Timesheet settings.", setting_row(get_setting(self.company())))

    def put(self, request):
        s, d = get_setting(self.company()), request.data
        try:
            for k in ("standard_daily_hours", "max_daily_hours", "overtime_multiplier"):
                if k in d:
                    v = to_decimal(d[k])
                    if v is None or v <= 0:
                        raise ValueError(f"{k} must be greater than 0.")
                    setattr(s, k, v)
            if s.standard_daily_hours > s.max_daily_hours or s.max_daily_hours > 24:
                raise ValueError("standard_daily_hours must not exceed max_daily_hours, and max_daily_hours must not exceed 24.")
            for k in ("auto_overtime", "enforce_allocation"):
                if k in d:
                    setattr(s, k, to_bool(d[k]))
            if "week_start_day" in d:
                w = to_int(d["week_start_day"])
                if w is None or not 0 <= w <= 6:
                    raise ValueError("week_start_day must be 0 (Monday) to 6 (Sunday).")
                s.week_start_day = w
            if "backdate_limit_days" in d:
                b = to_int(d["backdate_limit_days"])
                if b is None or b < 0:
                    raise ValueError("backdate_limit_days must be 0 or more.")
                s.backdate_limit_days = b
        except ValueError as ex:
            return err("VALIDATION", str(ex))
        s.updated_by = self.actor()
        s.save()
        return ok("TIMESHEET_SETTINGS_UPDATED", "Settings updated.", setting_row(s))

    patch = put
