"""
Сервис для работы с ЮKassa API.
"""
import uuid
import logging
from decimal import Decimal
from typing import Optional, Dict, Any

from django.conf import settings
from yookassa import Configuration, Payment as YooPayment

logger = logging.getLogger(__name__)


class YooKassaService:
    """Сервис для работы с ЮKassa."""
    
    def __init__(self):
        """Инициализация конфигурации ЮKassa."""
        if settings.YOOKASSA_SHOP_ID and settings.YOOKASSA_SECRET_KEY:
            Configuration.account_id = settings.YOOKASSA_SHOP_ID
            Configuration.secret_key = settings.YOOKASSA_SECRET_KEY
        else:
            logger.warning("ЮKassa credentials not configured")
    
    def create_payment(
        self,
        amount: Decimal,
        description: str,
        return_url: str,
        metadata: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """
        Создать платеж в ЮKassa.
        
        Args:
            amount: Сумма платежа
            description: Описание платежа
            return_url: URL для возврата после оплаты
            metadata: Дополнительные данные
        
        Returns:
            Словарь с данными платежа
        """
        try:
            idempotence_key = str(uuid.uuid4())
            
            payment = YooPayment.create({
                "amount": {
                    "value": str(amount),
                    "currency": "RUB"
                },
                "confirmation": {
                    "type": "redirect",
                    "return_url": return_url
                },
                "capture": True,
                "description": description,
                "metadata": metadata or {}
            }, idempotence_key)
            
            logger.info(f"Payment created: {payment.id}")
            
            return {
                'id': payment.id,
                'status': payment.status,
                'amount': payment.amount.value,
                'currency': payment.amount.currency,
                'confirmation_url': payment.confirmation.confirmation_url if payment.confirmation else None,
                'created_at': payment.created_at,
                'metadata': payment.metadata,
            }
        
        except Exception as e:
            logger.error(f"Error creating payment: {e}")
            raise Exception(f"Ошибка создания платежа: {str(e)}")
    
    def get_payment(self, payment_id: str) -> Dict[str, Any]:
        """
        Получить информацию о платеже.
        
        Args:
            payment_id: ID платежа в ЮKassa
        
        Returns:
            Словарь с данными платежа
        """
        try:
            payment = YooPayment.find_one(payment_id)
            
            return {
                'id': payment.id,
                'status': payment.status,
                'amount': payment.amount.value,
                'currency': payment.amount.currency,
                'paid': payment.paid,
                'created_at': payment.created_at,
                'metadata': payment.metadata,
                'payment_method': payment.payment_method.type if payment.payment_method else None,
            }
        
        except Exception as e:
            logger.error(f"Error getting payment {payment_id}: {e}")
            raise Exception(f"Ошибка получения платежа: {str(e)}")
    
    def cancel_payment(self, payment_id: str) -> Dict[str, Any]:
        """
        Отменить платеж.
        
        Args:
            payment_id: ID платежа в ЮKassa
        
        Returns:
            Словарь с данными платежа
        """
        try:
            idempotence_key = str(uuid.uuid4())
            payment = YooPayment.cancel(payment_id, idempotence_key)
            
            logger.info(f"Payment canceled: {payment_id}")
            
            return {
                'id': payment.id,
                'status': payment.status,
            }
        
        except Exception as e:
            logger.error(f"Error canceling payment {payment_id}: {e}")
            raise Exception(f"Ошибка отмены платежа: {str(e)}")


# Глобальный экземпляр сервиса
yookassa_service = YooKassaService()


