"""Notification service: send_notification for email, SMS, push, etc."""

import logging
from django.template import Template, Context
from django.utils import timezone
from apps.notifications.models import Notification, NotificationTemplate
from apps.notifications.email_delivery import send_email_using_active_config

def render_template(template_string, context):
	try:
		return Template(template_string).render(Context(context))
	except Exception as e:
		return template_string  # fallback

def send_notification(channel, recipient, template_code, context=None, user=None, tenant_id=None, provider=None):
	"""
	Send a notification via the specified channel using a template.
	Creates a Notification entry and updates status.
	"""
	logger = logging.getLogger(__name__)
	context = context or {}
	try:
		template = NotificationTemplate.objects.get(code=template_code, channel=channel, is_active=True)
	except NotificationTemplate.DoesNotExist:
		logger.error(f"NotificationTemplate not found: code={template_code}, channel={channel}")
		return {'ok': False, 'error': 'Template not found'}

	subject = render_template(template.subject_template, context)
	message = render_template(template.body_template, context)
	notification = Notification.objects.create(
		user=user,
		channel=channel,
		recipient=recipient,
		subject=subject,
		message=message,
		status='pending',
		provider=provider or '',
		tenant_id=tenant_id,
	)
	try:
		if channel == 'email':
			result = send_email_using_active_config(
				subject=subject,
				message=message,
				recipient_list=[recipient],
				purpose='notification',
			)
			if result.get('ok'):
				notification.status = 'sent'
				notification.sent_at = timezone.now()
				notification.provider = str(result.get('provider') or notification.provider or '')
				notification.save(update_fields=['status', 'sent_at', 'provider'])
				logger.info(f"Email sent to {recipient}")
				return {'ok': True, 'notification_id': str(notification.id), 'detail': result}

			notification.status = 'failed'
			notification.save(update_fields=['status'])
			logger.error(f"Email send blocked/failed for {recipient}: {result.get('error')}")
			return {'ok': False, 'error': result.get('error') or 'Email delivery failed'}
		# Future: add SMS, push, etc.
		else:
			notification.status = 'failed'
			notification.save(update_fields=['status'])
			logger.error(f"Channel not implemented: {channel}")
			return {'ok': False, 'error': 'Channel not implemented'}
	except Exception as e:
		notification.status = 'failed'
		notification.save(update_fields=['status'])
		logger.error(f"Failed to send notification: {e}")
		return {'ok': False, 'error': str(e)}
