"""
Send email verification function.
"""

from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, To

from apexsaas.exceptions import ApexEmailError, ApexValidationError
from apexsaas.email._templates import get_verification_template


def send_verification_email(
    to_email: str,
    to_name: str,
    verification_url: str,
    sendgrid_api_key: str,
    from_email: str,
    from_name: str = "Apex"
) -> dict:
    """
    Send email verification email.
    
    Args:
        to_email: Recipient email address
        to_name: Recipient name
        verification_url: URL for email verification
        sendgrid_api_key: SendGrid API key
        from_email: Sender email address
        from_name: Sender name (default: "Apex")
    
    Returns:
        dict with success status and message details
    
    Raises:
        ApexValidationError: If required parameters are missing
        ApexEmailError: If SendGrid API call fails
    """
    if not to_email or not to_name:
        raise ApexValidationError("to_email and to_name are required")
    if not verification_url:
        raise ApexValidationError("verification_url is required")
    if not sendgrid_api_key:
        raise ApexValidationError("sendgrid_api_key is required")
    if not from_email:
        raise ApexValidationError("from_email is required")
    
    try:
        # Get HTML template
        html_content = get_verification_template(verification_url, to_name)
        
        # Create message
        message = Mail(
            from_email=(from_email, from_name),
            to_emails=To(to_email),
            subject="Verify Your Email Address",
            html_content=html_content,
            plain_text_content=f"Please verify your email by visiting: {verification_url}"
        )
        
        # Send email
        client = SendGridAPIClient(api_key=sendgrid_api_key)
        response = client.send(message)
        
        # Check response
        if response.status_code not in [200, 201, 202]:
            raise ApexEmailError(f"SendGrid API error: {response.status_code}")
        
        return {
            'success': True,
            'message_id': response.headers.get('X-Message-Id', 'unknown'),
            'message': f'Verification email sent to {to_email}'
        }
    
    except Exception as e:
        if isinstance(e, (ApexValidationError, ApexEmailError)):
            raise
        raise ApexEmailError(f"Failed to send verification email: {str(e)}")

