"""Email notification service using Lambda API."""

import requests
import json
import logging
from typing import Optional
from datetime import datetime

logger = logging.getLogger(__name__)


class EmailNotifier:
    """Email notification service for payment events using Lambda API."""
    
    def __init__(self, api_endpoint: str = "https://wbkghwm2te.execute-api.us-east-1.amazonaws.com/prod/send-email"):
        self.api_endpoint = api_endpoint
        logger.info(f"EmailNotifier initialized with endpoint: {api_endpoint}")
    
    def _send_email(self, to_email: str, subject: str, body: str) -> bool:
        """Send email using Lambda API."""
        try:
            payload = {
                "to_email": to_email,
                "subject": subject,
                "body": body
            }
            
            headers = {
                "Content-Type": "application/json"
            }
            
            response = requests.post(
                self.api_endpoint,
                headers=headers,
                data=json.dumps(payload),
                timeout=30
            )
            
            if response.status_code == 200:
                logger.info(f"Email sent successfully to {to_email}")
                return True
            else:
                logger.error(f"Email API error: {response.status_code} - {response.text}")
                return False
                
        except requests.exceptions.RequestException as e:
            logger.error(f"Email API request failed: {e}")
            return False
        except Exception as e:
            logger.error(f"Unexpected error sending email: {e}")
            return False
    
    def notify_payment_success(self, transaction_id: str, amount: int, currency: str,
                              cardholder_name: str, email: str) -> bool:
        """Send payment success notification email."""
        
        subject = f"Payment Successful - Transaction {transaction_id}"
        
        body = f"""Dear {cardholder_name},

Your payment has been processed successfully!

Transaction Details:
- Transaction ID: {transaction_id}
- Amount: {amount/100:.2f} {currency}
- Date: {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} UTC
- Status: SUCCESS

Thank you for your payment.

Best regards,
Payment Team
"""
        
        return self._send_email(email, subject, body)
    
    def notify_payment_failure(self, transaction_id: str, amount: int, currency: str,
                              cardholder_name: str, email: str, reason: str) -> bool:
        """Send payment failure notification email."""
        
        subject = f"Payment Failed - Transaction {transaction_id}"
        
        body = f"""Dear {cardholder_name},

Unfortunately, your payment could not be processed.

Transaction Details:
- Transaction ID: {transaction_id}
- Amount: {amount/100:.2f} {currency}
- Date: {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} UTC
- Status: FAILED
- Reason: {reason}

Please check your payment details and try again, or contact our support team.

Best regards,
Payment Team
"""
        
        return self._send_email(email, subject, body)
    
    def notify_fraud_alert(self, transaction_id: str, amount: int, currency: str,
                          cardholder_name: str, email: str, reason: str) -> bool:
        """Send fraud alert notification email."""
        
        subject = f"Security Alert - Transaction {transaction_id}"
        
        body = f"""Dear {cardholder_name},

We detected suspicious activity on your payment attempt.

Transaction Details:
- Transaction ID: {transaction_id}
- Amount: {amount/100:.2f} {currency}
- Date: {datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S')} UTC
- Status: BLOCKED
- Reason: {reason}

If this was a legitimate transaction, please contact our support team.

Best regards,
Security Team
"""
        
        return self._send_email(email, subject, body)
    
    def send_custom_notification(self, email: str, subject: str, message: str) -> bool:
        """Send custom notification email."""
        return self._send_email(email, subject, message)