"""SNS notification service."""

import boto3
import json
import logging
from typing import Optional
from datetime import datetime
from botocore.exceptions import ClientError

logger = logging.getLogger(__name__)


class PaymentNotifier:
    """SNS notification service for payment events."""
    
    def __init__(self, topic_arn: str, region: str = "us-east-1"):
        self.topic_arn = topic_arn
        self.region = region
        self.sns_client = boto3.client("sns", region_name=region)
        logger.info(f"PaymentNotifier initialized with topic: {topic_arn}")
    
    def send_payment_notification(self, transaction_id: str, status: str, 
                                  amount: int, email: str) -> bool:
        """Send payment status notification."""
        try:
            message = {
                "transaction_id": transaction_id,
                "status": status,
                "amount": amount,
                "email": email,
                "timestamp": datetime.utcnow().isoformat()
            }
            
            subject = f"Payment {status}: Transaction {transaction_id}"
            
            response = self.sns_client.publish(
                TopicArn=self.topic_arn,
                Message=json.dumps(message, indent=2),
                Subject=subject
            )
            
            logger.info(f"Notification sent: {transaction_id} - {status}")
            return True
        except ClientError as e:
            logger.error(f"SNS publish failed: {e}")
            return False
    
    def send_fraud_alert(self, transaction_id: str, reason: str, amount: int) -> bool:
        """Send fraud detection alert."""
        try:
            message = {
                "alert_type": "FRAUD_DETECTED",
                "transaction_id": transaction_id,
                "reason": reason,
                "amount": amount,
                "timestamp": datetime.utcnow().isoformat()
            }
            
            subject = f"FRAUD ALERT: Transaction {transaction_id}"
            
            response = self.sns_client.publish(
                TopicArn=self.topic_arn,
                Message=json.dumps(message, indent=2),
                Subject=subject
            )
            
            logger.warning(f"Fraud alert sent: {transaction_id} - {reason}")
            return True
        except ClientError as e:
            logger.error(f"SNS fraud alert failed: {e}")
            return False
