from __future__ import annotations

from django.utils import timezone

from core.models import PortalConfiguration
from notifications.models import NotificationLog, NotificationTemplate


def _configuration():
    return PortalConfiguration.objects.order_by("pk").first()


def _status_for_automatic(config):
    if config and config.auto_send_notifications:
        return NotificationLog.Status.SCHEDULED
    return NotificationLog.Status.DRAFT


def prepare_ticket_message_notification(message):
    ticket = message.ticket
    config = _configuration()
    company = config.company_name if config else "Kreate4Web"
    base_url = (config.portal_base_url if config else "").rstrip("/")
    portal_path = f"/portal/tickets/{ticket.pk}/"
    portal_url = f"{base_url}{portal_path}" if base_url else portal_path

    if message.author_type == message.AuthorType.STAFF and not message.is_internal:
        recipient = (ticket.client.email or "").strip().lower()
        if not recipient:
            return None
        subject = f"[{ticket.reference}] Nova resposta da {company}"
        body = (
            f"Olá {ticket.client.name},\n\n"
            f"Existe uma nova resposta no ticket {ticket.reference}: {ticket.subject}.\n\n"
            f"{message.message}\n\n"
            f"Consulte e responda no portal: {portal_url}\n\n{company}"
        )
        html_body = (
            f"<div style='font-family:Arial,sans-serif;max-width:640px;margin:auto;color:#24262d'>"
            f"<div style='border-top:6px solid #ffd400;padding:22px;background:#fff'>"
            f"<h2 style='margin:0 0 8px;color:#111'>{company}</h2>"
            f"<p>Olá <strong>{ticket.client.name}</strong>,</p>"
            f"<p>Existe uma nova resposta no ticket <strong>{ticket.reference}</strong>: {ticket.subject}.</p>"
            f"<div style='padding:16px;border-radius:12px;background:#f5f5f5'>{message.message}</div>"
            f"<p><a href='{portal_url}' style='display:inline-block;padding:12px 18px;background:#111;color:#ffd400;text-decoration:none;border-radius:8px'>Abrir ticket</a></p>"
            f"</div></div>"
        )
        dedupe = f"support:staff:{message.pk}:{recipient}"
    elif message.author_type == message.AuthorType.CLIENT:
        recipient = ""
        if config:
            recipient = (config.internal_notification_email or config.company_email or "").strip().lower()
        if not recipient:
            return None
        subject = f"[{ticket.reference}] Nova mensagem do cliente"
        body = (
            f"O cliente {ticket.client.name} respondeu ao ticket {ticket.reference}: {ticket.subject}.\n\n"
            f"{message.message}\n\nAbra o backoffice para responder."
        )
        html_body = ""
        dedupe = f"support:client:{message.pk}:{recipient}"
    else:
        return None

    notification, _ = NotificationLog.objects.get_or_create(
        deduplication_key=dedupe,
        defaults={
            "client": ticket.client,
            "service": ticket.service,
            "channel": NotificationLog.Channel.EMAIL,
            "recipient": recipient,
            "reply_to": (config.reply_to_email or config.company_email) if config else "",
            "subject": subject,
            "body": body,
            "html_body": html_body,
            "status": _status_for_automatic(config),
            "scheduled_for": timezone.now() if config and config.auto_send_notifications else None,
            "is_automatic": True,
            "max_attempts": config.notification_max_attempts if config else 3,
        },
    )
    return notification


def prepare_ticket_resolved_notification(ticket):
    config = _configuration()
    recipient = (ticket.client.email or "").strip().lower()
    if not recipient:
        return None
    company = config.company_name if config else "Kreate4Web"
    dedupe = f"support:resolved:{ticket.pk}:{ticket.closed_at or ticket.updated_at}:{recipient}"
    body = (
        f"Olá {ticket.client.name},\n\n"
        f"O ticket {ticket.reference} — {ticket.subject} foi marcado como resolvido.\n"
        "Pode reabri-lo respondendo no portal, caso a situação persista.\n\n"
        f"{company}"
    )
    notification, _ = NotificationLog.objects.get_or_create(
        deduplication_key=dedupe,
        defaults={
            "client": ticket.client,
            "service": ticket.service,
            "channel": NotificationLog.Channel.EMAIL,
            "recipient": recipient,
            "subject": f"[{ticket.reference}] Ticket resolvido",
            "body": body,
            "status": _status_for_automatic(config),
            "scheduled_for": timezone.now() if config and config.auto_send_notifications else None,
            "is_automatic": True,
            "max_attempts": config.notification_max_attempts if config else 3,
        },
    )
    return notification
