"""Send a test email to verify SMTP configuration.

Usage:
    python manage.py test_email you@example.com

This sends a simple email using the project's EmailService and prints the
active SMTP settings, so you can confirm email works on any environment
(local or production) without going through the payment webhook.
"""

from __future__ import annotations

from django.conf import settings
from django.core.management.base import BaseCommand, CommandError

from apps.core.email import EmailService


class Command(BaseCommand):
    help = "Send a test email to verify SMTP configuration."

    def add_arguments(self, parser):
        parser.add_argument(
            "recipient",
            help="Email address to send the test message to.",
        )

    def handle(self, *args, **options):
        recipient = options["recipient"]

        # Show the active email configuration (password masked).
        self.stdout.write(self.style.MIGRATE_HEADING("Email configuration:"))
        self.stdout.write(f"  EMAIL_BACKEND     = {settings.EMAIL_BACKEND}")
        self.stdout.write(f"  EMAIL_HOST        = {settings.EMAIL_HOST}")
        self.stdout.write(f"  EMAIL_PORT        = {settings.EMAIL_PORT}")
        self.stdout.write(f"  EMAIL_HOST_USER   = {settings.EMAIL_HOST_USER}")
        self.stdout.write(
            f"  EMAIL_HOST_PASSWORD = {'*' * len(settings.EMAIL_HOST_PASSWORD or '')}"
        )
        self.stdout.write(f"  EMAIL_USE_TLS     = {settings.EMAIL_USE_TLS}")
        self.stdout.write(
            f"  EMAIL_USE_SSL     = {getattr(settings, 'EMAIL_USE_SSL', False)}"
        )
        self.stdout.write(f"  DEFAULT_FROM_EMAIL = {settings.DEFAULT_FROM_EMAIL}")
        self.stdout.write("")

        self.stdout.write(f"Sending test email to {recipient} ...")

        try:
            sent = EmailService.send(
                to=recipient,
                subject="RfoofPay — SMTP Test",
                message=(
                    "This is a test email from RfoofPay.\n\n"
                    "If you received this, your SMTP configuration is working "
                    "correctly.\n\n"
                    "— RfoofPay"
                ),
                fail_silently=False,
            )
        except Exception as exc:
            raise CommandError(f"Failed to send email: {exc}") from exc

        if sent:
            self.stdout.write(
                self.style.SUCCESS(f"✓ Email sent successfully to {recipient}")
            )
        else:
            raise CommandError("EmailService reported failure (returned False).")
