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


class Command(BaseCommand):
    help = "Send a test email through the configured SMTP backend to verify credentials."

    def add_arguments(self, parser):
        parser.add_argument("--to", required=True, help="Recipient email address")

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

        if not settings.EMAIL_HOST_USER or not settings.EMAIL_HOST_PASSWORD:
            raise CommandError(
                "EMAIL_HOST_USER / EMAIL_HOST_PASSWORD are not set. "
                "Check your .env file."
            )

        self.stdout.write(
            f"Sending via {settings.EMAIL_HOST}:{settings.EMAIL_PORT} "
            f"as {settings.EMAIL_HOST_USER} -> {recipient} ..."
        )

        send_mail(
            subject="TAI AfroPress SMTP test",
            message="If you received this, the Zoho SMTP configuration is working.",
            from_email=settings.DEFAULT_FROM_EMAIL,
            recipient_list=[recipient],
            fail_silently=False,
        )

        self.stdout.write(self.style.SUCCESS(f"Sent. Check {recipient}'s inbox."))
