"""Shift lookups that name a person: yourself, or someone else by name/code.

The live gap this locks down, in shift_query_node's permission handling:

Naming YOURSELF was refused your own record. is_targeted_lookup was
bool(employee_id or employee_name) — "was anyone named?", never "is the
named person me?" — so an employee asking "what is geo1's shift" when
geo1 is their own emp_no got TEAMMATE_SHIFT_DENIAL for their own shift.
ownership_guard closed this hole one node upstream and then deliberately
waves shift phrasings through because THIS node "applies its own permission
check", so the self-identity half has to live here or it falls between
the two nodes — which is exactly what happened.

Who the route answers for depends on the caller's role: an ordinary
employee gets their own shift and nothing else, while a manager, HR user or
admin may also name a team member — see TestTeammateDenialStillHolds
(employee) and TestNamedTargetsAreRoleGated (both). The role is resolved by
shift_query._may_view_team_shifts, which fails closed, and erp-api remains
the authority on who is actually in the caller's team.

The denial cases are the other half of the contract: every widening here is
paired with the refusal it must NOT weaken.
"""

import pytest

import services.shift_query as shift_query


CALLER_NAME = "A GeoFencing"
CALLER_EMP_NO = "geo1"
CALLER_USER_ID = 704

ROSTER = [
    {"employee_id": 3735, "employee_number": "geo3", "employee_name": "Ayush Jio"},
    {"employee_id": 3759, "employee_number": "geo6", "employee_name": "A Emp"},
    {"employee_id": 3772, "employee_number": "geo11", "employee_name": "Akash geo A"},
]

SHIFT = {
    "shift_id": 242, "shift_name": "General-Shift", "shift_code": None,
    "shift_type": "NORMAL", "start_time": "09:00:00", "end_time": "18:30:00",
    "working_minutes": 570, "break_time_minutes": 30, "relief_time_minutes": 0,
    "week_off_day": ["Sunday"], "status": "1", "is_general_shift": True,
    "is_readonly": True,
    "session_summary": {"total_sessions": 0, "total_working_minutes": 0,
                        "total_break_time_minutes": 0, "total_relief_time_minutes": 0},
    "sessions": [],
}


class FakeWriter:
    def __init__(self):
        self.events = []

    def __call__(self, event):
        self.events.append(event)

    def of_type(self, etype):
        return [e for e in self.events if e.get("type") == etype]


def state(query: str, is_manager, is_hr_role=None) -> dict:
    return {"query": query, "intent": "shift_query", "usage_events": [],
            "bearer_token": "caller-token", "company_id": 1,
            "conversation_id": "conv-1", "is_manager": is_manager,
            "is_hr_role": is_hr_role}


@pytest.fixture(autouse=True)
def _caller_identity(monkeypatch):
    """The JWT claims shift_query_node reads to know who is asking."""
    monkeypatch.setattr(shift_query.attendance_mod, "_decode_jwt_claims",
                        lambda token: {"name": CALLER_NAME, "emp_no": CALLER_EMP_NO,
                                       "user_id": CALLER_USER_ID})


def mock_target(monkeypatch, employee_id=None, employee_name=None):
    async def _fake(query, today=None):
        return {"employee_id": employee_id, "employee_name": employee_name,
                "requested_date": None}, None
    monkeypatch.setattr(shift_query.ai_service, "extract_shift_target_fields", _fake)


def mock_erp(monkeypatch, calls):
    """erp-api by the rules it actually follows: a name search matches the
    NAME field only and otherwise returns the whole roster; an employee_id
    returns that person's shift with an attribution block; no target at all
    returns the caller's own shift, unattributed."""
    async def _fake(token, company_id=None, conversation_id=None,
                    employee_id=None, employee_name=None):
        calls.append({"employee_id": employee_id, "employee_name": employee_name})
        if employee_id is not None:
            row = next((e for e in ROSTER if e["employee_id"] == employee_id), None)
            data = {"shift": dict(SHIFT)}
            if row:
                data["employee"] = {"employee_name": row["employee_name"],
                                    "employee_number": row["employee_number"]}
            return {"http_status": 200, "body": {"success": True, "data": data}}
        if employee_name:
            hits = [e for e in ROSTER
                    if employee_name.strip().lower() in e["employee_name"].lower()]
            return {"http_status": 200, "body": {"success": True, "data": {
                "action_required": "select_employee",
                "search_matched": bool(hits),
                "employees": hits or list(ROSTER),
            }}}
        return {"http_status": 200, "body": {"success": True,
                                             "data": {"shift": dict(SHIFT)}}}
    monkeypatch.setattr(shift_query.erp_client, "get_active_shift", _fake)


def denied(writer):
    return any(e.get("data", {}).get("denied")
               for e in writer.of_type("shift_summary"))


# ═════════════════════════════════════════════════════════════════════════════
# Naming yourself is a self lookup, not a teammate lookup
# ═════════════════════════════════════════════════════════════════════════════

class TestSelfReference:

    @pytest.mark.parametrize("query,extracted_name", [
        ("what is geo1's shift", "geo1"),
        ("show geo1 shift details", "geo1"),
        ("what is A GeoFencing's shift", "A GeoFencing"),
    ])
    async def test_own_emp_no_or_name_is_not_refused(self, monkeypatch, query, extracted_name):
        mock_target(monkeypatch, employee_name=extracted_name)
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(state(query, False), writer)

        assert not denied(writer)
        assert "General-Shift" in result["response_text"]

    async def test_self_reference_sends_no_target_to_erp(self, monkeypatch):
        """Downgraded to an own-shift lookup, so the caller's own token is
        what selects the record — this cannot widen access to anyone."""
        mock_target(monkeypatch, employee_name="geo1")
        calls = []
        mock_erp(monkeypatch, calls)

        await shift_query.shift_query_node(state("what is geo1's shift", False), FakeWriter())

        assert calls == [{"employee_id": None, "employee_name": None}]

    async def test_self_reference_answer_is_worded_as_your_own(self, monkeypatch):
        """Not "geo1 is currently assigned..." — it is the caller's own card."""
        mock_target(monkeypatch, employee_name="geo1")
        mock_erp(monkeypatch, [])

        result = await shift_query.shift_query_node(
            state("what is geo1's shift", False), FakeWriter())

        assert result["response_text"].startswith("You're currently assigned")

    async def test_a_manager_naming_themselves_also_gets_their_own(self, monkeypatch):
        mock_target(monkeypatch, employee_name="geo1")
        calls = []
        mock_erp(monkeypatch, calls)

        result = await shift_query.shift_query_node(
            state("what is geo1's shift", True), FakeWriter())

        assert calls == [{"employee_id": None, "employee_name": None}]
        assert "General-Shift" in result["response_text"]


# ═════════════════════════════════════════════════════════════════════════════
# Naming yourself by numeric employee ID is also a self lookup
# ═════════════════════════════════════════════════════════════════════════════
#
# Live gap: _mentions_own_identity only ever text-searches the query for the
# caller's NAME or emp_no — a bare numeric id ("shift details of employee
# 704") carries neither substring, so it was indistinguishable from a
# teammate's id and got denied the caller's own record. The JWT's own
# "user_id" claim IS the caller's erp employee_id (confirmed against a live
# token: user_id 3754 for emp_no DEMO0604262, role_name "hr"), so it is now
# compared directly against the structured extraction instead.

class TestSelfReferenceByEmployeeId:

    async def test_own_employee_id_is_not_refused(self, monkeypatch):
        mock_target(monkeypatch, employee_id=CALLER_USER_ID)
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            state(f"shift details of employee {CALLER_USER_ID}", False), writer)

        assert not denied(writer)
        assert "General-Shift" in result["response_text"]

    async def test_own_employee_id_sends_no_target_to_erp(self, monkeypatch):
        mock_target(monkeypatch, employee_id=CALLER_USER_ID)
        calls = []
        mock_erp(monkeypatch, calls)

        await shift_query.shift_query_node(
            state(f"shift details of employee {CALLER_USER_ID}", False), FakeWriter())

        assert calls == [{"employee_id": None, "employee_name": None}]

    async def test_own_employee_id_answer_is_worded_as_your_own(self, monkeypatch):
        mock_target(monkeypatch, employee_id=CALLER_USER_ID)
        mock_erp(monkeypatch, [])

        result = await shift_query.shift_query_node(
            state(f"shift details of employee {CALLER_USER_ID}", False), FakeWriter())

        assert result["response_text"].startswith("You're currently assigned")

    async def test_a_manager_naming_their_own_id_also_gets_their_own(self, monkeypatch):
        mock_target(monkeypatch, employee_id=CALLER_USER_ID)
        calls = []
        mock_erp(monkeypatch, calls)

        result = await shift_query.shift_query_node(
            state(f"shift details of employee {CALLER_USER_ID}", True), FakeWriter())

        assert calls == [{"employee_id": None, "employee_name": None}]
        assert "General-Shift" in result["response_text"]

    async def test_a_different_employee_id_is_denied_for_an_employee(self, monkeypatch):
        """The exact-match guarantee: a teammate's id (even one digit off)
        must never accidentally self-match."""
        other_id = ROSTER[0]["employee_id"]
        assert other_id != CALLER_USER_ID
        mock_target(monkeypatch, employee_id=other_id)
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            state(f"shift details of employee {other_id}", False), writer)

        assert denied(writer)
        assert result["response_text"] == shift_query.TEAMMATE_SHIFT_DENIAL
        assert calls == []

    async def test_a_different_employee_id_is_fetched_as_a_target_for_a_manager(self, monkeypatch):
        """Same exact-match guarantee from the other side: the id is NOT
        read as the caller's own, so it reaches erp-api as a TARGET rather
        than silently returning the manager's own shift."""
        other_id = ROSTER[0]["employee_id"]
        mock_target(monkeypatch, employee_id=other_id)
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            state(f"shift details of employee {other_id}", True), writer)

        assert not denied(writer)
        assert calls == [{"employee_id": other_id, "employee_name": None}]
        assert "Ayush Jio" in result["response_text"]


# ═════════════════════════════════════════════════════════════════════════════
# The denial this must not weaken
# ═════════════════════════════════════════════════════════════════════════════

class TestTeammateDenialStillHolds:

    @pytest.mark.parametrize("is_manager", [False, "unknown", None])
    async def test_someone_else_is_refused_for_an_unprivileged_caller(self, monkeypatch, is_manager):
        """An ordinary employee — and a caller whose role erp-api could not
        confirm, which fails closed — never gets a teammate's shift."""
        mock_target(monkeypatch, employee_name="geo3")
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            state("what is geo3's shift", is_manager), writer)

        assert denied(writer)
        assert result["response_text"] == shift_query.TEAMMATE_SHIFT_DENIAL
        assert calls == [], "denied pre-fetch — no erp call for a teammate (AC3)"

    async def test_a_confirmed_manager_may_look_up_a_team_member(self, monkeypatch):
        """The reversal of the old self-only rule: erp-api is asked, and it
        is erp-api that decides whether that employee is in their team."""
        mock_target(monkeypatch, employee_name="geo3")
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            state("what is geo3's shift", True), writer)

        assert not denied(writer)
        assert calls == [{"employee_id": None, "employee_name": "geo3"}]
        assert result["response_text"] != shift_query.TEAMMATE_SHIFT_DENIAL

    async def test_an_hr_caller_may_look_up_a_team_member(self, monkeypatch):
        """is_hr_role comes from the same /leave/context response is_manager
        does, and grants the same view."""
        mock_target(monkeypatch, employee_name="geo3")
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        await shift_query.shift_query_node(
            state("what is geo3's shift", False, is_hr_role=True), writer)

        assert not denied(writer)
        assert calls == [{"employee_id": None, "employee_name": "geo3"}]

    @pytest.mark.parametrize("role_name", ["admin", "Administrator", "super_admin"])
    async def test_an_admin_jwt_may_look_up_a_team_member(self, monkeypatch, role_name):
        """erp-api's context response carries no is_admin, so an admin is
        recognisable from the JWT role claim alone."""
        monkeypatch.setattr(shift_query.attendance_mod, "_decode_jwt_claims",
                            lambda token: {"name": CALLER_NAME, "emp_no": CALLER_EMP_NO,
                                           "user_id": CALLER_USER_ID, "role_name": role_name})
        mock_target(monkeypatch, employee_name="geo3")
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        await shift_query.shift_query_node(
            state("what is geo3's shift", False), writer)

        assert not denied(writer)
        assert calls == [{"employee_id": None, "employee_name": "geo3"}]

    async def test_an_ordinary_jwt_role_grants_nothing(self, monkeypatch):
        """The JWT half is an ALLOW list, not "any role claim will do"."""
        monkeypatch.setattr(shift_query.attendance_mod, "_decode_jwt_claims",
                            lambda token: {"name": CALLER_NAME, "emp_no": CALLER_EMP_NO,
                                           "user_id": CALLER_USER_ID, "role_name": "employee"})
        mock_target(monkeypatch, employee_name="geo3")
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            state("what is geo3's shift", False), writer)

        assert denied(writer)
        assert result["response_text"] == shift_query.TEAMMATE_SHIFT_DENIAL
        assert calls == []

    async def test_a_partial_name_overlap_is_not_a_self_match(self, monkeypatch):
        """"Akash geo A" shares a token with nobody's full name here, but the
        matcher requires the caller's FULL name or an exact emp_no — a loose
        substring must never grant a self match."""
        mock_target(monkeypatch, employee_name="geo11")
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        await shift_query.shift_query_node(state("what is geo11's shift", False), writer)

        assert denied(writer)
        assert calls == []

    async def test_denial_names_no_employee(self, monkeypatch):
        """Fixed string, no target detail — it cannot be used to enumerate."""
        mock_target(monkeypatch, employee_name="geo3")
        mock_erp(monkeypatch, [])

        result = await shift_query.shift_query_node(
            state("what is geo3's shift", False), FakeWriter())

        for row in ROSTER:
            assert row["employee_name"] not in result["response_text"]
            assert row["employee_number"] not in result["response_text"]


# ═════════════════════════════════════════════════════════════════════════════
# Employee-code lookups ("what is geo3's shift") follow the same role rule
# as name lookups: refused for an employee, forwarded to erp-api for a
# manager/HR/admin, which resolves the code against the caller's own team.
# TestTeammateDenialStillHolds covers the "geo3" case across the role
# values; this class adds what that one doesn't: several different codes,
# and the exact-match-not-substring guarantee for a NON-self code (geo11
# must not be confused with the caller's own geo1).
# ═════════════════════════════════════════════════════════════════════════════

class TestNamedTargetsAreRoleGated:

    @pytest.mark.parametrize("code", ["geo3", "geo6", "geo11"])
    async def test_any_teammate_code_is_denied_for_an_employee(self, monkeypatch, code):
        mock_target(monkeypatch, employee_name=code)
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            state(f"what is {code}'s shift", False), writer)

        assert denied(writer)
        assert result["response_text"] == shift_query.TEAMMATE_SHIFT_DENIAL
        assert calls == []

    @pytest.mark.parametrize("code", ["geo3", "geo6", "geo11"])
    async def test_any_teammate_code_is_resolved_for_a_manager(self, monkeypatch, code):
        mock_target(monkeypatch, employee_name=code)
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        await shift_query.shift_query_node(
            state(f"what is {code}'s shift", True), writer)

        assert not denied(writer)
        assert calls and calls[0]["employee_name"] == code

    async def test_a_real_name_is_denied_for_an_employee(self, monkeypatch):
        mock_target(monkeypatch, employee_name="Ayush")
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            state("what is Ayush's shift", False), writer)

        assert denied(writer)
        assert "Ayush Jio" not in result["response_text"]
        assert calls == []

    async def test_a_non_self_code_never_matches_the_callers_own_via_substring(self, monkeypatch):
        """"geo11" must not be confused with the caller's own "geo1" — an
        exact match only. For an employee that means a denial; for a manager
        it means the lookup goes to erp-api as a TARGET rather than quietly
        answering with the caller's own shift."""
        mock_target(monkeypatch, employee_name="geo11")
        calls = []
        mock_erp(monkeypatch, calls)

        writer = FakeWriter()
        result = await shift_query.shift_query_node(
            state("what is geo11's shift", False), writer)

        assert denied(writer)
        assert "Akash geo A" not in result["response_text"]
        assert calls == []

        calls.clear()
        await shift_query.shift_query_node(
            state("what is geo11's shift", True), FakeWriter())

        assert calls == [{"employee_id": None, "employee_name": "geo11"}]
