"""SES email service for receipts."""

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

logger = logging.getLogger(__name__)


class PaymentMailer:
    """SES email service for payment receipts."""
    
    def __init__(self, sender_email: str, region: str = "us-east-1"):
        self.sender_email = sender_email
        self.region = region
        self.ses_client = boto3.client("ses", region_name=region)
        logger.info(f"PaymentMailer initialized with sender: {sender_email}")
    
    def send_payment_receipt(self, recipient_email: str, transaction_id: str, 
                           amount: int, cardholder_name: str, masked_card: str) -> bool:
        """Send payment receipt email."""
        try:
            subject = f"Payment Receipt - Transaction {transaction_id}"
            
            body_text = f"""
Payment Receipt

Transaction ID: {transaction_id}
Amount: ${amount/100:.2f}
Cardholder: {cardholder_name}
Card: {masked_card}
Status: SUCCESS

Thank you for your payment!

This is an automated message. Please do not reply.
            """.strip()
            
            body_html = f"""
<html>
<head></head>
<body>
    <h2>Payment Receipt</h2>
    <table border="1" cellpadding="5" cellspacing="0">
        <tr><td><strong>Transaction ID:</strong></td><td>{transaction_id}</td></tr>
        <tr><td><strong>Amount:</strong></td><td>${amount/100:.2f}</td></tr>
        <tr><td><strong>Cardholder:</strong></td><td>{cardholder_name}</td></tr>
        <tr><td><strong>Card:</strong></td><td>{masked_card}</td></tr>
        <tr><td><strong>Status:</strong></td><td>SUCCESS</td></tr>
    </table>
    <p>Thank you for your payment!</p>
    <p><em>This is an automated message. Please do not reply.</em></p>
</body>
</html>
            """
            
            response = self.ses_client.send_email(
                Source=self.sender_email,
                Destination={'ToAddresses': [recipient_email]},
                Message={
                    'Subject': {'Data': subject},
                    'Body': {
                        'Text': {'Data': body_text},
                        'Html': {'Data': body_html}
                    }
                }
            )
            
            logger.info(f"Receipt sent to {recipient_email} for transaction {transaction_id}")
            return True
        except ClientError as e:
            error_code = e.response['Error']['Code']
            if error_code == 'MessageRejected':
                logger.error(f"Email rejected: {recipient_email}")
            elif error_code == 'MailFromDomainNotVerifiedException':
                logger.error(f"Sender email not verified: {self.sender_email}")
            else:
                logger.error(f"SES send failed: {e}")
            return False
