# -*- coding: utf-8 -*-
from __future__ import annotations

import uuid

from hotpocket_backend.apps.saves.services import (
    SavesService as BackendSavesService,
)
from hotpocket_soa.dto.saves import SaveIn, SaveOut

from .base import ProxyService, SOAError


class SavesService(ProxyService):
    class SavesServiceError(SOAError):
        pass

    class SaveNotFound(SavesServiceError):
        pass

    def wrap_exception(self, exception: Exception) -> Exception:
        new_exception_args = []
        if len(exception.args) > 0:
            new_exception_args = [exception.args[0]]

        return self.SavesServiceError(*new_exception_args)

    def __init__(self):
        super().__init__()
        self.backend_saves_service = BackendSavesService()

    def create(self, *, account_uuid: uuid.UUID, save: SaveIn) -> SaveOut:
        return SaveOut.model_validate(
            self.call(
                self.backend_saves_service,
                'create',
                account_uuid=account_uuid,
                save=save,
            ),
            from_attributes=True,
        )

    def get(self, *, pk: uuid.UUID) -> SaveOut:
        try:
            result = SaveOut.model_validate(
                self.call(
                    self.backend_saves_service,
                    'get',
                    pk=pk,
                ),
                from_attributes=True,
            )

            return result
        except SOAError as exception:
            if isinstance(exception.__cause__, BackendSavesService.SaveNotFound) is True:
                raise self.SaveNotFound(*exception.args) from exception
            else:
                raise
