from aiohttp.web import Request, Response
from aiohttp.web_response import json_response
from smb.common.pgswim.lib.engine import SwimEngine

from maps_adv.geosmb.cleaner.server.lib.domain import Domain
from maps_adv.geosmb.cleaner.server.lib.exceptions import (
    NoUserTicketException,
    ValidationException,
)


class Resources:
    __slots__ = ["_db", "_domain"]

    _db: SwimEngine
    _domain: Domain

    def __init__(self, db: SwimEngine, domain: Domain):
        self._db = db
        self._domain = domain

    async def ping(self, _: Request) -> Response:
        await self._db.healthcheck()

        return Response(status=204)

    async def register_client_for_delete(self, request: Request) -> Response:
        request_id = request.rel_url.query.get("request_id")
        if not request_id:
            raise ValidationException("request_id query param is missed or empty")

        if "X-Ya-User-Ticket" not in request.headers:
            raise NoUserTicketException

        await self._domain.register_client_for_delete(
            tvm_user_ticket=request.headers["X-Ya-User-Ticket"],
            request_id=request_id,
        )

        return json_response({"status": "ok"})

    async def retrieve_client_status(self, request: Request) -> Response:
        if "X-Ya-User-Ticket" not in request.headers:
            raise NoUserTicketException

        status, update_date = await self._domain.retrieve_client_status(
            tvm_user_ticket=request.headers["X-Ya-User-Ticket"],
        )

        return json_response(
            {
                "status": "ok",
                "data": [
                    {
                        "id": "1",
                        "slug": "all",
                        "state": status,
                        "update_date": update_date.isoformat() if update_date else None,
                    }
                ],
            }
        )
