<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
use Throwable;

class DiagnoseMail extends Command
{
    protected $signature = 'mail:diagnose {--to= : Send a test email to this address after authentication}';

    protected $description = 'Check the configured SMTP connection and authentication without sending mail by default';

    public function handle(): int
    {
        $recipient = $this->option('to');
        if ($recipient && ! filter_var($recipient, FILTER_VALIDATE_EMAIL)) {
            $this->error('Provide a valid test recipient.');
            return self::FAILURE;
        }

        $name = config('mail.default');
        $config = config("mail.mailers.{$name}", []);
        if (($config['transport'] ?? null) !== 'smtp') {
            $this->error('The default mailer is not SMTP. No mail sent.');
            return self::FAILURE;
        }

        $this->line('Configuration cached: '.(app()->configurationIsCached() ? 'yes' : 'no'));
        $transport = null;
        try {
            $mailer = Mail::mailer($name);
            $transport = $mailer->getSymfonyTransport();
            if (! $transport instanceof EsmtpTransport) {
                $this->error('The resolved transport is not SMTP. No mail sent.');
                return self::FAILURE;
            }

            $transport->getStream()->setTimeout(15);
            $this->line('Transport: '.(string) $transport);
            $this->line('Username: '.$transport->getUsername());
            $this->line('From: '.config('mail.from.address'));
            $transport->start();
            $this->info('SMTP connection and authentication succeeded.');

            if ($recipient) {
                $mailer->raw('Desxpert SMTP delivery test. No account action is required.', function ($message) use ($recipient) {
                    $message->to($recipient)->subject('Desxpert email delivery test');
                });
                $this->info('SMTP server accepted the test email. Check the recipient inbox and spam folder to confirm delivery.');
            } else {
                $this->line('No email sent. Use --to=address@example.com to test submission.');
            }

            return self::SUCCESS;
        } catch (Throwable $exception) {
            $message = $exception->getMessage();
            $password = $transport instanceof EsmtpTransport ? $transport->getPassword() : ($config['password'] ?? '');
            foreach (array_filter([$password, $password ? base64_encode($password) : '', $config['url'] ?? '']) as $secret) {
                $message = str_replace($secret, '[redacted]', $message);
            }
            $this->output->writeln($message, \Symfony\Component\Console\Output\OutputInterface::OUTPUT_RAW);
            return self::FAILURE;
        } finally {
            if ($transport instanceof EsmtpTransport) {
                try {
                    $transport->stop();
                } catch (Throwable) {
                    // Preserve the original SMTP diagnostic if cleanup fails.
                }
            }
        }
    }
}
