<?php

namespace App\Console\Commands;

use App\Models\MailingBounce;
use App\Models\User;
use App\Mail\TransferReceived;
use App\Mail\NewMessageMail;
use App\Mail\ContactFormMailable;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;

class TestUniversalBounceSystem extends Command
{
    /**
     * The name and signature of the console command.
     */
    protected $signature = 'test:universal-bounce
                            {--email= : Email to test (default: creates test emails)}
                            {--scenario= : Test scenario: suppressed, normal, mixed}
                            {--mailable= : Test specific mailable: transfer, contact, all}';

    /**
     * The console command description.
     */
    protected $description = 'Test universal bounce handling system with different mailable types';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $scenario = $this->option('scenario') ?: 'suppressed';
        $email = $this->option('email');
        $mailable = $this->option('mailable') ?: 'all';

        $this->info('🧪 Testing Universal Bounce Handling System');

        switch ($scenario) {
            case 'suppressed':
                $this->testSuppressedEmail($email, $mailable);
                break;
            case 'normal':
                $this->testNormalEmail($email, $mailable);
                break;
            case 'mixed':
                $this->testMixedRecipients($mailable);
                break;
            default:
                $this->error("Unknown scenario: {$scenario}");
                $this->info("Available scenarios: suppressed, normal, mixed");
                return 1;
        }

        return 0;
    }

    /**
     * Test sending to suppressed email (should be blocked)
     */
    protected function testSuppressedEmail(?string $email, string $mailable): void
    {
        $testEmail = $email ?: 'test-suppressed@example.com';

        $this->info("📧 Testing suppressed email: {$testEmail}");

        // Ensure the email is suppressed
        MailingBounce::suppressEmail($testEmail, 'Test suppression for universal bounce system');

        $this->line("✅ Email {$testEmail} is now suppressed");

        // Test different mailable types
        if ($mailable === 'all' || $mailable === 'contact') {
            $this->testContactFormMailable($testEmail);
        }

        if ($mailable === 'all' || $mailable === 'transfer') {
            $this->testTransferMailable($testEmail);
        }

        $this->info("📊 Check your logs to see if suppressed emails were blocked");
    }

    /**
     * Test sending to normal email (should work)
     */
    protected function testNormalEmail(?string $email, string $mailable): void
    {
        $testEmail = $email ?: 'test-normal@example.com';

        $this->info("📧 Testing normal email: {$testEmail}");

        // Ensure the email is not suppressed
        MailingBounce::where('email', $testEmail)->delete();

        $this->line("✅ Email {$testEmail} is not suppressed");

        // Test different mailable types
        if ($mailable === 'all' || $mailable === 'contact') {
            $this->testContactFormMailable($testEmail);
        }

        if ($mailable === 'all' || $mailable === 'transfer') {
            $this->testTransferMailable($testEmail);
        }

        $this->info("📊 Check Mailpit at http://localhost:8025 to see sent emails");
    }

    /**
     * Test mixed recipients (some suppressed, some normal)
     */
    protected function testMixedRecipients(string $mailable): void
    {
        $this->info("📧 Testing mixed recipients (some suppressed, some normal)");

        // Set up test data
        $suppressedEmail = 'suppressed-mixed@example.com';
        $normalEmail = 'normal-mixed@example.com';

        MailingBounce::suppressEmail($suppressedEmail, 'Test mixed recipients');
        MailingBounce::where('email', $normalEmail)->delete();

        $this->line("✅ Set up mixed recipient scenario");

        // Note: This test would require modifying existing mailables to support multiple recipients
        // or creating a special test mailable. For now, we'll test individually.

        $this->line("Testing suppressed email in mixed scenario...");
        $this->testContactFormMailable($suppressedEmail);

        $this->line("Testing normal email in mixed scenario...");
        $this->testContactFormMailable($normalEmail);

        $this->info("📊 Check logs and Mailpit to verify behavior");
    }

    /**
     * Test ContactFormMailable
     */
    protected function testContactFormMailable(string $email): void
    {
        $this->line("  Testing ContactFormMailable to: {$email}");

        $contactData = [
            'email' => $email,
            'name' => 'Test User',
            'message' => 'Universal bounce test message'
        ];

        try {
            // This will use the universal bounce handler via the MessageSending event
            Mail::to($email)->send(new ContactFormMailable($contactData));
            $this->line("  ✅ ContactFormMailable sent (or blocked by bounce handler)");
        } catch (\Exception $e) {
            $this->error("  ❌ Error sending ContactFormMailable: " . $e->getMessage());
        }
    }

    /**
     * Test TransferMailable (requires a user)
     */
    protected function testTransferMailable(string $email): void
    {
        $this->line("  Testing TransferReceived to: {$email}");

        // Create or find a test user
        $user = User::where('email', $email)->first();
        if (!$user) {
            $user = User::create([
                'name' => 'Bounce Test User',
                'email' => $email,
                'password' => bcrypt('password'),
            ]);
        }

        // Create a mock transaction (this is simplified for testing)
        try {
            // Note: TransferReceived requires a Transaction model which has complex relationships
            // For testing purposes, we'll just try to send a simple contact form instead
            $this->line("  (Skipping TransferReceived test - requires full transaction setup)");
            $this->testContactFormMailable($email);
        } catch (\Exception $e) {
            $this->error("  ❌ Error with transfer test: " . $e->getMessage());
        }
    }
}