#  Copyright (C) 2025
#  ABM, Moscow
#
#  UNPUBLISHED PROPRIETARY MATERIAL.
#  ALL RIGHTS RESERVED.
#
#  Authors: Mikhail Mamrov <m.mamrov@abm-jsc.ru>
#
import logging
from dataclasses import dataclass, asdict
from enum import StrEnum, unique

from http_tools import AbmServiceConnector
from init_helpers import dict_to_dataclass

logger = logging.getLogger(__name__)


@dataclass(frozen=True, slots=True)
class TicketCreationInitiator:
    email: str
    name: str


@dataclass(frozen=True, slots=True)
class TicketCreationPayload:
    title: str
    description: str
    service_id: str
    initiator: TicketCreationInitiator
    requires_monitoring: bool = False


@dataclass(frozen=True, slots=True)
class TicketClosurePayload:
    link: str
    initiator_id: str
    solution_message: str


@unique
class TicketStatusCode(StrEnum):
    CREATED = "created"
    REGISTERED = "registered"
    IN_PROGRESS = "in_progress"
    DONE = "done"
    DELETED = "deleted"
    REJECTED = "rejected"
    CLOSED = "closed"
    CLOSED_WITH_REJECTED = "closed_with_rejected"


@dataclass(frozen=True, slots=True)
class Ticket:
    type: str
    link: str
    number: str
    executor_id: str
    status_code: TicketStatusCode
    
    
class SUTPGatewayConnector:
    _SERVER_NAME_HEADER = "server_name"

    Config = AbmServiceConnector.Config

    @dataclass
    class Context(AbmServiceConnector.Context):
        server_name: str

    def __init__(self, config: Config, context: Context) -> None:
        self.config = config
        self.context = context
        self._connector = AbmServiceConnector(config, context)
        logger.info(f"{type(self).__name__} inited")

    async def create_ticket(self, ticket_creation_payload: TicketCreationPayload) -> Ticket:
        answer = await self._connector.post(
            path="/v1/ticket/create",
            payload={"ticket_creation_payload": asdict(ticket_creation_payload)},
            headers={self._SERVER_NAME_HEADER: self.context.server_name},
        )

        ticket = dict_to_dataclass(answer, Ticket)
        logger.info(f"Successfully created {ticket = }")
        return ticket

    async def get_ticket(self, link: str) -> Ticket:
        answer = await self._connector.get(
            path="/v1/ticket/get",
            url_query={"link": link},
            headers={self._SERVER_NAME_HEADER: self.context.server_name},
        )

        return dict_to_dataclass(answer, Ticket)

    async def close_ticket(self, ticket_closure_payload: TicketClosurePayload) -> bool:
        return await self._connector.patch(
            path="/v1/ticket/close",
            payload={"ticket_closure_payload": asdict(ticket_closure_payload)},
            headers={self._SERVER_NAME_HEADER: self.context.server_name},
        )
