from django.core.management import call_command
from django.core.management.base import BaseCommand

from core.models import PortalConfiguration
from notifications.models import NotificationTemplate
from notifications.scheduling import ensure_notification_schedule
from monitoring.scheduling import ensure_monitoring_schedule


class Command(BaseCommand):
    help = "Cria configuração, modelos de notificação e agendamentos iniciais."

    def handle(self, *args, **options):
        config = PortalConfiguration.objects.order_by("pk").first()
        if not config:
            config = PortalConfiguration.objects.create(
                company_name="Kreate4Web",
                company_email="criamos@kreative4web.com",
                email_test_mode=True,
                auto_prepare_notifications=True,
                auto_send_notifications=False,
                notification_max_attempts=3,
                notification_retry_minutes=30,
            )
        elif not config.company_name or config.company_name == "Gestão de Serviços Web":
            config.company_name = "Kreate4Web"
            config.save(update_fields=["company_name", "updated_at"])

        templates = [
            ("renewal-30", "renewal_30", "Renovação de {servico} — faltam 30 dias"),
            ("renewal-15", "renewal_15", "Lembrete de renovação de {servico}"),
            ("renewal-7", "renewal_7", "Aviso urgente: renovação de {servico}"),
            ("renewal-due", "due", "Renovação hoje: {servico}"),
            ("service-overdue", "overdue", "Serviço vencido: {servico}"),
            ("payment-received", "payment_received", "Pagamento recebido — {servico}"),
            ("renewal-confirmed", "renewal_confirmed", "Renovação confirmada — {servico}"),
            ("support-created", "support_created", "Ticket criado — Kreate4Web"),
            ("support-reply", "support_reply", "Nova resposta de suporte — Kreate4Web"),
            ("support-resolved", "support_resolved", "Ticket resolvido — Kreate4Web"),
            ("monitor-down", "monitor_down", "Alerta: {website} está indisponível"),
            ("monitor-recovered", "monitor_recovered", "Recuperado: {website} está novamente operacional"),
        ]
        body = (
            "Olá {cliente},\n\n"
            "Informamos que o serviço {servico} tem renovação em {data_renovacao}, "
            "no valor de {valor}.\n\n"
            "Método de pagamento preferencial: {metodo_pagamento}.\n"
            "MB WAY: {mbway}\nIBAN: {iban}\n\n"
            "Com os melhores cumprimentos,\n{empresa}\n{email_empresa} · {telefone_empresa}"
        )
        html_body = (
            "<div style='font-family:Arial,sans-serif;max-width:640px;margin:auto;color:#20304a'>"
            "<h2 style='color:#111;border-left:6px solid #ffd400;padding-left:12px'>{empresa}</h2>"
            "<p>Olá <strong>{cliente}</strong>,</p>"
            "<p>Informamos que o serviço <strong>{servico}</strong> tem renovação em "
            "<strong>{data_renovacao}</strong>, no valor de <strong>{valor}</strong>.</p>"
            "<div style='padding:16px;border-radius:10px;background:#f4f8ff'>"
            "<p style='margin:0 0 6px'><strong>Método preferencial:</strong> {metodo_pagamento}</p>"
            "<p style='margin:0 0 6px'><strong>MB WAY:</strong> {mbway}</p>"
            "<p style='margin:0'><strong>IBAN:</strong> {iban}</p></div>"
            "<p>Com os melhores cumprimentos,<br><strong>{empresa}</strong><br>"
            "{email_empresa} · {telefone_empresa}</p></div>"
        )
        monitor_body = (
            "Olá {cliente},\n\n"
            "Estado de monitorização do website {website}.\n"
            "URL: {url}\nMotivo: {motivo}\n\n"
            "A equipa {empresa} está a acompanhar a situação."
        )
        monitor_html = (
            "<div style='font-family:Arial,sans-serif;max-width:640px;margin:auto;color:#20304a'>"
            "<h2 style='border-left:6px solid #ffd400;padding-left:12px'>{empresa}</h2>"
            "<p>Olá <strong>{cliente}</strong>,</p>"
            "<p>Estado de monitorização de <strong>{website}</strong>.</p>"
            "<p><strong>URL:</strong> {url}<br><strong>Motivo:</strong> {motivo}</p>"
            "<p>A equipa está a acompanhar a situação.</p></div>"
        )
        for code, notification_type, subject in templates:
            is_monitor = notification_type in {"monitor_down", "monitor_recovered"}
            NotificationTemplate.objects.update_or_create(
                code=code,
                defaults={
                    "notification_type": notification_type,
                    "subject_template": subject,
                    "body_template": monitor_body if is_monitor else body,
                    "html_body_template": monitor_html if is_monitor else html_body,
                    "is_active": True,
                    "allow_automatic_send": True,
                    "send_to_billing_contacts": not is_monitor,
                },
            )
        ensure_notification_schedule()
        ensure_monitoring_schedule()
        call_command("seed_template_library", verbosity=0)
        self.stdout.write(self.style.SUCCESS("Configuração, templates e automação inicial criados."))
