<?php

namespace App\Console\Commands;

use App\Models\User;
use App\Models\Mailing;
use App\Models\MailingBounce;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

class TestMailpitIntegration extends Command
{
    /**
     * The name and signature of the console command.
     */
    protected $signature = 'test:mailpit-integration
                            {--send-test : Send a test email via Mailpit}
                            {--test-suppression : Test that suppressed emails are blocked}';

    /**
     * The console command description.
     */
    protected $description = 'Test Mailpit integration and bounce suppression';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        if ($this->option('send-test')) {
            $this->sendTestEmail();
        }

        if ($this->option('test-suppression')) {
            $this->testSuppressionInSending();
        }

        if (!$this->option('send-test') && !$this->option('test-suppression')) {
            $this->info('Available options:');
            $this->line('  --send-test         Send a test email via Mailpit');
            $this->line('  --test-suppression  Test that suppressed emails are blocked');
        }

        return 0;
    }

    /**
     * Send a test email via Mailpit
     */
    protected function sendTestEmail(): void
    {
        $this->info('🧪 Testing Email Sending via Mailpit');

        // Create a test user
        $testUser = User::where('email', 'mailpit-test@example.com')->first();
        if (!$testUser) {
            $testUser = User::create([
                'name' => 'Mailpit Test User',
                'email' => 'mailpit-test@example.com',
                'password' => bcrypt('password'),
            ]);
            $testUser->forceFill(['email_verified_at' => now()])->save();
        }

        // Send a simple test email
        try {
            Mail::raw('This is a test email from the bounce handling system!', function ($message) use ($testUser) {
                $message->to($testUser->email)
                       ->subject('Bounce System Test Email')
                       ->from('test@timebank.cc', 'Timebank Test');
            });

            $this->info("✅ Test email sent to: {$testUser->email}");
            $this->line("📧 Check Mailpit at: http://localhost:8025");
            $this->line("💡 The email should appear in your Mailpit inbox");

        } catch (\Exception $e) {
            $this->error("❌ Failed to send email: " . $e->getMessage());
        }
    }

    /**
     * Test that suppressed emails are blocked from sending
     */
    protected function testSuppressionInSending(): void
    {
        $this->info('🧪 Testing Suppression During Email Sending');

        // Use one of our test suppressed emails
        $suppressedEmail = 'suppressed@example.com';

        // Verify it's actually suppressed
        $isSuppressed = MailingBounce::isSuppressed($suppressedEmail);
        $this->line("Email {$suppressedEmail} suppressed: " . ($isSuppressed ? 'YES' : 'NO'));

        if (!$isSuppressed) {
            $this->warn("Email is not suppressed. Run the bounce tests first:");
            $this->line("php artisan test:bounce-system --scenario=multiple");
            return;
        }

        // Find the user
        $user = User::where('email', $suppressedEmail)->first();
        if (!$user) {
            $this->warn("User not found. Run the bounce tests first.");
            return;
        }

        // Try to send an email (this should be blocked)
        $this->line("Attempting to send email to suppressed address...");

        try {
            // This is how the actual mailing system would check
            if (MailingBounce::isSuppressed($user->email)) {
                $this->info("✅ SUCCESS: Email sending was blocked for suppressed address");
                $this->line("   This is the expected behavior - suppressed emails are not sent");
            } else {
                $this->error("❌ FAILED: Suppressed email was not blocked");
            }

        } catch (\Exception $e) {
            $this->error("❌ Error during suppression test: " . $e->getMessage());
        }

        // Show bounce stats for this email
        $stats = MailingBounce::getBounceStats($suppressedEmail);
        $this->line("\nBounce Statistics for {$suppressedEmail}:");
        $this->line("  Total bounces: {$stats['total_bounces']}");
        $this->line("  Recent hard bounces: {$stats['recent_hard_bounces']}");
        $this->line("  Is suppressed: " . ($stats['is_suppressed'] ? 'YES' : 'NO'));
    }
}