"""Row buttons on the regularization tables, and the design's display fields
(AI Regularization Manager View, 2026-10-06):

  * the employee's OWN table (any role): only a `cancel` key, true on a
    Pending row.
  * a Manager/HR/Admin's TEAM table: only `approve` and `reject`, true on a
    Pending row.
  * every table: total_count.
  * every row: date from-to, 12-hour in/out time.
"""
from datetime import datetime

import pytest

import services.erp_client as erp_client
import services.regularisation_approval as ra
import services.regularisation_display as display
from services.my_regularisation_view import my_regularisation_view_node


def _row(rid, status, name="B Geo"):
    return {"regularization_id": rid, "apply_date": "2026-09-12", "from_time": "09:15:00",
            "to_time": "19:00:00", "reason": "Forgot to punch out", "status_name": status,
            "employee_id": 1, "employee_number": "geo3", "employee_name": name,
            "created_at": "2026-09-10 08:00:00"}


ALL = [_row(1, "pending"), _row(2, "approved"), _row(3, "rejected"), _row(4, "cancelled")]


class Writer(list):
    def __call__(self, e):
        self.append(e)

    def done(self):
        return [e for e in self if e.get("type") == "done"][-1]


def _ok(rows):
    return {"http_status": 200, "body": {"success": True, "data": {"regularizations": rows}}}


class TestFlags:
    @pytest.mark.parametrize("status,cancel", [("pending", True), ("approved", False),
                                               ("rejected", False), ("cancelled", False)])
    def test_employee(self, status, cancel):
        assert display.employee_actions(_row(1, status)) == {"cancel": cancel}

    @pytest.mark.parametrize("status,acts", [("pending", True), ("approved", False),
                                             ("rejected", False), ("cancelled", False)])
    def test_approver(self, status, acts):
        assert display.approver_actions(_row(1, status)) == {"approve": acts, "reject": acts}

    def test_numeric_status_codes_are_understood(self):
        assert display.status_key({"status": 2}) == "rejected"
        assert display.status_key({"status": 3}) == "cancelled"


class TestMyTable:
    async def test_cancel_only_on_pending(self, monkeypatch):
        async def mine(token, status=None, **kw):
            return _ok([dict(r) for r in ALL])

        monkeypatch.setattr(erp_client, "get_my_regularizations", mine)
        w = Writer()
        await my_regularisation_view_node({"query": "show my regularization requests",
                                           "company_id": 1, "conversation_id": "c",
                                           "bearer_token": "t", "usage_events": []}, w)
        data = w.done()["data"]
        rows = {r["regularization_id"]: r for r in data["regularizations"]}
        assert rows[1]["cancel"] is True
        assert all(rows[i]["cancel"] is False for i in (2, 3, 4))
        # Only the key this table uses.
        assert not any("approve" in r or "reject" in r for r in rows.values())
        assert data["total_count"] == 4


class TestTeamTable:
    async def test_approve_and_reject_only_on_pending(self, monkeypatch):
        team = [_row(10, "pending", "Arjun Menon"), _row(11, "approved", "Sneha Pillai")]

        async def pending(token, employee_id=None, **kw):
            return {"http_status": 200, "body": {"success": True, "data": {
                "total_pending_regularizations": 1, "regularizations": [dict(r) for r in team]}}}

        monkeypatch.setattr(erp_client, "get_pending_regularizations", pending)
        w = Writer()
        await ra.regularisation_approval_node(
            {"query": "show pending regularization requests", "intent": ra.VIEW_INTENT,
             "company_id": 1, "conversation_id": "c", "bearer_token": "t", "usage_events": [],
             "is_manager": True, "is_manager_jwt": True}, w)

        data = w.done()["data"]
        rows = {r["regularization_id"]: r for r in data["regularizations"]}
        assert (rows[10]["approve"], rows[10]["reject"]) == (True, True)
        assert not any("cancel" in r for r in rows.values()), "only the keys this table uses"
        assert data["total_count"] == 1
        assert (rows[11]["approve"], rows[11]["reject"]) == (False, False)
        assert data["title"] == "Pending regularization requests (1)"
        assert data["subtitle"] == "Waiting for your action, oldest first."


class TestDisplayFields:
    def test_row(self):
        r = display.enrich_row(_row(10452, "pending"))
        assert r["date_from"] == r["date_to"] == "2026-09-12"
        assert r["date_range_display"] == "12-Sep-2026 – 12-Sep-2026"
        assert (r["in_time_display"], r["out_time_display"]) == ("9:15 AM", "7:00 PM")
        assert r["applied_on_display"] == "10-Sep-2026"

    def test_action_time(self):
        assert display.action_time_display(datetime(2026, 10, 5, 10, 24)) == "05-Oct-2026, 10:24 AM"
