# ============================================================
# ADDITIVE: Employee self-service - My Assets
# Mounted from hrnexus/urls.py as:  path('employee/assets/', include('People.views_employee_assets'))
# Auth: Employee JWT only. An employee sees / acts on OWN allocations only - the employee is ALWAYS taken
# from the token (request.user); no employee code / id is ever accepted from the client (no IDOR).
# Purchase cost, vendor, internal notes and other custodians are never returned.
#
#   GET   /employee/assets/                  my assets   ?status=assigned|returned|pending_return|unacknowledged
#                                                         ?search=  ?page=  ?page_size=
#   GET   /employee/assets/summary/          counters (assigned / returned / pending return / to acknowledge)
#   GET   /employee/assets/pending-returns/  my assets HR asked me to return (or exit clearance) + due date
#   GET   /employee/assets/history/          my returned assets
#   GET   /employee/assets/<id>/             one of my allocations (id = allocation id)
#   POST  /employee/assets/<id>/acknowledge/ {note?}  confirm receipt (second call -> 409)
# ============================================================
from django.db import transaction
from django.db.models import Q
from django.urls import path
from django.utils import timezone
from rest_framework.views import APIView

from Employee.employee_authentication import EmployeeJWTAuthentication, IsEmployeeAuthenticated
from Employee.employee_crud_permissions import actor_label

from .common import err, iso, ok, paginate
from .models import AssetAllocation, ExitClearance

ACTIVE_EXIT = ("Initiated", "In Progress", "Cleared")


class MyAssetBase(APIView):
    authentication_classes = [EmployeeJWTAuthentication]
    permission_classes = [IsEmployeeAuthenticated]

    @property
    def me(self):
        return self.request.user

    def company(self):
        return self.request.user.company

    def mine(self):
        """Only the logged-in employee's own, active allocation rows of the same company."""
        return (AssetAllocation.objects.filter(company=self.company(), employee=self.me, is_active=True,
                                               asset__is_active=True, asset__company=self.company())
                .select_related("asset"))

    def my_exit(self):
        return (ExitClearance.objects.filter(company=self.company(), employee=self.me, is_active=True,
                                             status__in=ACTIVE_EXIT).order_by("-id").first())

    def row(self, al, ex=None):
        a = al.asset
        in_exit = ex is not None and al.status == "Allocated"
        pending = bool(al.status == "Allocated" and (al.return_pending or in_exit))
        due = al.return_due_date or (ex.last_working_day if in_exit else None)
        today = timezone.localdate()
        if al.status == "Returned":
            label = "Returned"
        elif pending:
            label = "Return Pending"
        elif al.acknowledged_on is None:
            label = "Awaiting Acknowledgement"
        else:
            label = "Assigned"
        return {
            "id": al.id,
            "asset_id": a.id,
            "asset_tag": a.asset_tag,
            "device_name": a.device_name,
            "category": a.category,
            "serial_number": a.serial_number,
            "warranty_until": iso(a.warranty_until),
            "allocated_on": iso(al.allocated_on),
            "expected_return": iso(al.expected_return),
            "returned_on": iso(al.returned_on),
            "condition_out": al.condition_out,
            "condition_in": al.condition_in,
            "status": al.status,
            "display_status": label,
            "return_pending": pending,
            "return_requested_on": iso(al.return_requested_on),
            "return_due_date": iso(due),
            "return_overdue": bool(pending and due and due < today),
            "return_reason": al.return_reason or ("Exit / offboarding" if in_exit else None),
            "acknowledged": al.acknowledged_on is not None,
            "acknowledged_on": al.acknowledged_on.isoformat() if al.acknowledged_on else None,
            "can_acknowledge": bool(al.status == "Allocated" and al.acknowledged_on is None),
        }


class MyAssets(MyAssetBase):
    def get(self, request):
        qs = self.mine()
        p = request.query_params
        st = (p.get("status") or "").strip().lower()
        if st in ("assigned", "allocated", "active"):
            qs = qs.filter(status="Allocated")
        elif st == "returned":
            qs = qs.filter(status="Returned")
        elif st == "pending_return":
            ex = self.my_exit()
            qs = qs.filter(status="Allocated") if ex else qs.filter(status="Allocated", return_pending=True)
        elif st == "unacknowledged":
            qs = qs.filter(status="Allocated", acknowledged_on__isnull=True)
        elif st:
            return err("VALIDATION", "Invalid status. Use assigned, returned, pending_return or unacknowledged.")
        q = (p.get("search") or "").strip()
        if q:
            qs = qs.filter(Q(asset__asset_tag__icontains=q) | Q(asset__device_name__icontains=q)
                           | Q(asset__serial_number__icontains=q) | Q(asset__category__icontains=q))
        ex = self.my_exit()
        rows, meta = paginate(request, qs, lambda al: self.row(al, ex))
        return ok("MY_ASSETS_LIST", "My assets fetched.", rows, meta=meta)


class MyAssetsSummary(MyAssetBase):
    def get(self, request):
        qs, ex = self.mine(), self.my_exit()
        open_qs = qs.filter(status="Allocated")
        pending = open_qs.count() if ex else open_qs.filter(return_pending=True).count()
        data = {
            "assigned": open_qs.count(),
            "returned": qs.filter(status="Returned").count(),
            "pending_return": pending,
            "awaiting_acknowledgement": open_qs.filter(acknowledged_on__isnull=True).count(),
            "in_exit_process": ex is not None,
            "last_working_day": iso(ex.last_working_day) if ex else None,
        }
        return ok("MY_ASSETS_SUMMARY", "Summary fetched.", data)


class MyPendingReturns(MyAssetBase):
    def get(self, request):
        ex = self.my_exit()
        qs = self.mine().filter(status="Allocated")
        if not ex:
            qs = qs.filter(return_pending=True)
        rows, meta = paginate(request, qs, lambda al: self.row(al, ex))
        return ok("MY_ASSETS_PENDING_RETURNS", "Pending returns fetched.", rows, meta=meta)


class MyAssetHistory(MyAssetBase):
    def get(self, request):
        qs = self.mine().filter(status="Returned").order_by("-returned_on", "-id")
        rows, meta = paginate(request, qs, self.row)
        return ok("MY_ASSETS_HISTORY", "Returned assets fetched.", rows, meta=meta)


class MyAssetDetail(MyAssetBase):
    def get(self, request, pk):
        al = self.mine().filter(pk=pk).first()
        if al is None:
            return err("NOT_FOUND", "Asset not found.", 404)
        return ok("MY_ASSET_DETAIL", "Asset fetched.", self.row(al, self.my_exit()))


class MyAssetAcknowledge(MyAssetBase):
    def post(self, request, pk):
        data = request.data if isinstance(request.data, dict) else {}
        note = (str(data.get("note") or "").strip() or None)
        if note and len(note) > 250:
            return err("VALIDATION", "note cannot exceed 250 characters.")
        with transaction.atomic():
            al = self.mine().select_for_update().filter(pk=pk).first()
            if al is None:
                return err("NOT_FOUND", "Asset not found.", 404)
            if al.status != "Allocated":
                return err("CONFLICT", "This asset has already been returned.", 409)
            if al.acknowledged_on is not None:
                return err("CONFLICT", "Receipt already acknowledged.", 409)
            al.acknowledged_on, al.acknowledged_note = timezone.now(), note
            al.updated_by = actor_label(self.me)
            al.save()
        return ok("MY_ASSET_ACKNOWLEDGED", "Receipt acknowledged.", self.row(al, self.my_exit()))


urlpatterns = [
    path("", MyAssets.as_view(), name="my_assets"),
    path("summary/", MyAssetsSummary.as_view(), name="my_assets_summary"),
    path("pending-returns/", MyPendingReturns.as_view(), name="my_assets_pending_returns"),
    path("history/", MyAssetHistory.as_view(), name="my_assets_history"),
    path("<int:pk>/", MyAssetDetail.as_view(), name="my_asset_detail"),
    path("<int:pk>/acknowledge/", MyAssetAcknowledge.as_view(), name="my_asset_acknowledge"),
]
