from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.conf import settings
import logging

logger = logging.getLogger(__name__)


class CareerEmailService:
    """Service for handling career-related emails"""
    
    def send_application_confirmation(self, application):
        """
        Send confirmation email to applicant
        """
        try:
            subject = f"Application Received - {application.job.title}"
            from_email = settings.DEFAULT_FROM_EMAIL
            to_email = [application.email]
            
            # Create context for email template
            context = {
                'applicant_name': application.full_name,
                'job_title': application.job.title,
                'job_location': application.job.location,
                'application_date': application.applied_date,
            }
            
            # Render email templates
            text_content = render_to_string('career/application_confirmation.txt', context)
            html_content = render_to_string('career/application_confirmation.html', context)
            
            # Create email
            email = EmailMultiAlternatives(
                subject=subject,
                body=text_content,
                from_email=from_email,
                to=to_email
            )
            email.attach_alternative(html_content, "text/html")
            
            # Send email
            email.send(fail_silently=False)
            
            logger.info(f"Confirmation email sent to {application.email}")
            return True
            
        except Exception as e:
            logger.error(f"Failed to send confirmation email: {str(e)}", exc_info=True)
            return False
    
    def send_application_notification_to_admin(self, application):
        """
        Send notification email to company about new application
        """
        try:
            subject = f"New Job Application: {application.job.title} - {application.full_name}"
            from_email = settings.DEFAULT_FROM_EMAIL
            to_email = [settings.COMPANY_EMAIL]
            
            # Create context for email template
            context = {
                'applicant_name': application.full_name,
                'applicant_email': application.email,
                'applicant_phone': application.phone,
                'job_title': application.job.title,
                'current_position': application.current_position,
                'current_company': application.current_company,
                'years_of_experience': application.years_of_experience,
                'cover_letter': application.cover_letter,
                'portfolio_url': application.portfolio_url,
                'linkedin_url': application.linkedin_url,
                'github_url': application.github_url,
                'website_url': application.website_url,
                'expected_salary': application.expected_salary,
                'salary_currency': application.salary_currency,
                'available_from': application.available_from,
                'notice_period': application.notice_period,
                'application_date': application.applied_date,
                'resume_url': application.resume.url if application.resume else None,
            }
            
            # Render email templates
            text_content = render_to_string('career/application_notification.txt', context)
            html_content = render_to_string('career/application_notification.html', context)
            
            # Create email
            email = EmailMultiAlternatives(
                subject=subject,
                body=text_content,
                from_email=from_email,
                to=to_email,
                reply_to=[application.email]
            )
            email.attach_alternative(html_content, "text/html")
            
            # Attach resume if available
            if application.resume:
                email.attach_file(application.resume.path)
            
            # Send email
            email.send(fail_silently=False)
            
            logger.info(f"Admin notification email sent for application from {application.email}")
            return True
            
        except Exception as e:
            logger.error(f"Failed to send admin notification email: {str(e)}", exc_info=True)
            return False

