from __future__ import annotations

from typing import Callable
from uuid import UUID, uuid4

from fastapi import HTTPException
from fastapi.testclient import TestClient

from app import app
from v1.schedule_items.dependencies import get_schedule_item_service
from v1.schedule_items.schemas import (
    ScheduleItemShareRequest,
    ScheduleItemShareResponse,
)
from v1.schedule_items.service import ScheduleItemService


class FakeScheduleItemShareService:
    def __init__(self, item_id: UUID) -> None:
        self._item_id = item_id
        self.last_share_request: ScheduleItemShareRequest | None = None

    async def share(
        self,
        item_id: UUID,
        request: ScheduleItemShareRequest,
    ) -> ScheduleItemShareResponse:
        if item_id != self._item_id:
            raise HTTPException(status_code=404, detail="Schedule item not found")
        self.last_share_request = request
        return ScheduleItemShareResponse(message="Calendar invitation sent")


def _override_schedule_item_service(
    service: FakeScheduleItemShareService,
) -> Callable[[], ScheduleItemService]:
    def _get_service() -> ScheduleItemService:
        return service  # type: ignore[return-value]

    return _get_service


def test_share_schedule_item_returns_200() -> None:
    item_id = uuid4()
    service = FakeScheduleItemShareService(item_id=item_id)
    app.dependency_overrides[get_schedule_item_service] = (
        _override_schedule_item_service(service)
    )

    client = TestClient(app)
    try:
        response = client.post(
            f"/api/v1/schedule-items/{item_id}/share",
            json={
                "email": "friend@example.com",
                "permission_view": True,
                "permission_edit": False,
                "permission_invite": True,
            },
        )
        assert response.status_code == 200
        body = response.json()
        assert body["message"] == "Calendar invitation sent"
        assert service.last_share_request is not None
        assert service.last_share_request.email == "friend@example.com"
        assert service.last_share_request.permission_invite is True
    finally:
        app.dependency_overrides = {}
