<?php

namespace Tests\Unit\Models;

use App\Models\Email;
use App\Models\Message;
use App\Models\ZEmail;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Cookie;
use ReflectionClass;
use Tests\TestCase;

class ZEmailTest extends TestCase
{
    protected function setUp(): void
    {
        parent::setUp();

        // Mock configuration
        Config::set('app.settings.imap_settings', json_encode([
            'host' => 'imap.gmail.com',
            'port' => 993,
            'protocol' => 'imap',
            'encryption' => 'ssl',
            'validate_cert' => true,
            'username' => 'test@gmail.com',
            'password' => 'password',
        ]));

        Config::set('app.settings.configuration_settings', json_encode([
            'custom_username_length_min' => 3,
            'custom_username_length_max' => 20,
            'random_username_length_min' => 6,
            'random_username_length_max' => 12,
            'forbidden_ids' => ['admin', 'root', 'test'],
            'gmailUsernames' => ['john.doe', 'jane.smith'],
            'outlookUsernames' => ['outlookuser', 'testuser'],
            'domains' => ['gmail.com', 'outlook.com', 'example.com'],
        ]));

        Config::set('app.beta_feature', false);
        Config::set('app.force_db_mail', false);
        Config::set('app.fetch_from_db', false);

        // Clear cookies before each test
        Cookie::queue('email', '', -1);
        Cookie::queue('emails', serialize([]), -1);
    }

    /** @test */
    public function it_returns_null_when_no_email_cookie_exists_and_generate_is_false(): void
    {
        $result = ZEmail::getEmail(false);

        $this->assertNull($result);
    }

    /** @test */
    public function it_generates_random_email_when_no_cookie_exists_and_generate_is_true(): void
    {
        $result = ZEmail::getEmail(true);

        $this->assertIsString($result);
        $this->assertStringContainsString('@', $result);
    }

    /** @test */
    public function it_creates_custom_email_with_valid_username_length(): void
    {
        $result = ZEmail::createCustomEmail('validuser', 'example.com');

        $this->assertEquals('validuser@example.com', $result);
    }

    /** @test */
    public function it_generates_random_username_when_custom_username_is_too_short(): void
    {
        $result = ZEmail::createCustomEmail('ab', 'example.com'); // Less than min length 3

        $this->assertIsString($result);
        $this->assertStringContainsString('@example.com', $result);
        $username = explode('@', $result)[0];
        $this->assertGreaterThanOrEqual(3, strlen($username));
    }

    /** @test */
    public function it_generates_random_username_when_custom_username_is_too_long(): void
    {
        $longUsername = str_repeat('a', 25); // More than max length 20
        $result = ZEmail::createCustomEmail($longUsername, 'example.com');

        $this->assertIsString($result);
        $this->assertStringContainsString('@example.com', $result);
        $username = explode('@', $result)[0];
        $this->assertLessThanOrEqual(20, strlen($username));
    }

    /** @test */
    public function it_sanitizes_username_by_removing_special_characters(): void
    {
        $result = ZEmail::createCustomEmail('user!@#$%', 'example.com');

        $this->assertEquals('user@example.com', $result);
    }

    /** @test */
    public function it_generates_random_email_when_forbidden_id_is_used(): void
    {
        $result = ZEmail::createCustomEmail('admin', 'example.com');

        $this->assertNotEquals('admin@example.com', $result);
        $this->assertStringContainsString('@', $result);
    }

    /** @test */
    public function it_generates_random_gmail_when_empty_username_for_gmail_domain(): void
    {
        $result = ZEmail::createCustomEmail('', 'gmail.com');

        $this->assertStringContainsString('@gmail.com', $result);
        $this->assertNotEquals('@gmail.com', $result);
    }

    /** @test */
    public function it_generates_random_outlook_when_empty_username_for_outlook_domain(): void
    {
        $result = ZEmail::createCustomEmail('', 'outlook.com');

        $this->assertStringContainsString('@outlook.com', $result);
        $this->assertStringContainsString('+', $result);
    }

    /** @test */
    public function it_handles_gmail_plus_addressing_correctly(): void
    {
        $result = ZEmail::createCustomEmail('john.doe+tag', 'gmail.com');

        $this->assertEquals('john.doe+tag@gmail.com', $result);
    }

    /** @test */
    public function it_handles_gmail_dot_addressing_correctly(): void
    {
        $result = ZEmail::createCustomEmail('johndoe', 'gmail.com');

        $this->assertStringContainsString('@gmail.com', $result);
        $this->assertStringContainsString('+', $result);
    }

    /** @test */
    public function it_handles_outlook_plus_addressing_correctly(): void
    {
        $result = ZEmail::createCustomEmail('outlookuser+tag', 'outlook.com');

        $this->assertEquals('outlookuser+tag@outlook.com', $result);
    }

    /** @test */
    public function it_generates_random_email_for_unknown_domain(): void
    {
        $result = ZEmail::createCustomEmail('user', 'unknown.com');

        $this->assertNotEquals('user@unknown.com', $result);
        $this->assertStringContainsString('@', $result);
    }

    /** @test */
    public function it_generates_random_email_with_store_option(): void
    {
        $result = ZEmail::generateRandomEmail(true);

        $this->assertIsString($result);
        $this->assertStringContainsString('@', $result);
    }

    /** @test */
    public function it_generates_random_email_without_store_option(): void
    {
        $result = ZEmail::generateRandomEmail(false);

        $this->assertIsString($result);
        $this->assertStringContainsString('@', $result);
    }

    /** @test */
    public function it_generates_gmail_email_with_dots(): void
    {
        $result = ZEmail::generateRandomGmail(true);

        $this->assertMatchesRegularExpression('/.*@(gmail\.com|googlemail\.com)$/i', $result);
        $this->assertStringContainsString('@', $result);
    }

    /** @test */
    public function it_generates_outlook_email_with_plus_addressing(): void
    {
        $result = ZEmail::generateRandomOutlook(true);

        $this->assertStringContainsString('@outlook.com', $result);
        $this->assertStringContainsString('+', $result);
    }

    /** @test */
    public function it_generates_pronounceable_word(): void
    {
        $zemail = new ZEmail;
        $reflection = new ReflectionClass($zemail);
        $method = $reflection->getMethod('generatePronounceableWord');

        $result = $method->invoke($zemail);

        $this->assertIsString($result);
        $this->assertEquals(6, strlen($result)); // 2 iterations * 3 characters each
    }

    /** @test */
    public function it_generates_random_string_with_specified_length(): void
    {
        $zemail = new ZEmail;
        $reflection = new ReflectionClass($zemail);
        $method = $reflection->getMethod('generateRandomString');

        $result = $method->invoke($zemail, 10);

        $this->assertIsString($result);
        $this->assertEquals(10, strlen($result));
        $this->assertEquals(1, preg_match('/^[0-9a-z]+$/', $result));
    }

    /** @test */
    public function it_gets_random_domain_from_configuration(): void
    {
        $zemail = new ZEmail;
        $reflection = new ReflectionClass($zemail);
        $method = $reflection->getMethod('getRandomDomain');

        $result = $method->invoke($zemail);

        $this->assertContains($result, ['gmail.com', 'outlook.com', 'example.com']);
    }

    /** @test */
    public function it_gets_random_gmail_user_from_configuration(): void
    {
        $zemail = new ZEmail;
        $reflection = new ReflectionClass($zemail);
        $method = $reflection->getMethod('getRandomGmailUser');

        $result = $method->invoke($zemail);

        $this->assertContains($result, ['john.doe', 'jane.smith']);
    }

    /** @test */
    public function it_gets_random_outlook_user_from_configuration(): void
    {
        $zemail = new ZEmail;
        $reflection = new ReflectionClass($zemail);
        $method = $reflection->getMethod('getRandomOutlookUser');

        $result = $method->invoke($zemail);

        $this->assertContains($result, ['outlookuser', 'testuser']);
    }

    /** @test */
    public function it_returns_messages_from_message_model_when_beta_feature_is_enabled(): void
    {
        Config::set('app.beta_feature', true);
        Config::set('app.settings.configuration_settings', json_encode([
            'fetch_messages_limit' => 15,
            'enable_masking_external_link' => false,
            'blocked_domains' => ['spam.com'],
        ]));

        // Create a test message that will be found by getMessages
        Message::factory()->create([
            'to' => 'test@example.com',
            'subject' => 'Test Subject',
            'from' => 'Test Sender <sender@example.com>',
            'body' => 'Test body content',
        ]);

        $result = ZEmail::getMessages('test@example.com');

        // Should return the structured response from Message::getMessages
        $this->assertIsArray($result);
        $this->assertArrayHasKey('data', $result);
        $this->assertArrayHasKey('notifications', $result);
        $this->assertCount(1, $result['data']);
        $this->assertEquals('Test Subject', $result['data'][0]['subject']);
    }

    /** @test */
    public function it_returns_messages_from_email_model_when_force_db_mail_is_enabled(): void
    {
        Config::set('app.beta_feature', false);
        Config::set('app.force_db_mail', true);
        Config::set('app.settings.configuration_settings', json_encode([
            'fetch_messages_limit' => 15,
            'blocked_domains' => ['spam.com'],
            'date_format' => 'd M Y h:i A',
        ]));

        // Create a test email that will be found by parseEmail
        Email::factory()->create([
            'to' => ['test@example.com'],
            'is_seen' => false,
            'message_id' => 'test-123',
            'subject' => 'Test Subject',
            'from_name' => 'Test Sender',
            'from_email' => 'sender@example.com',
        ]);

        $result = ZEmail::getMessages('test@example.com');

        // Should return the structured response from parseEmail
        $this->assertIsArray($result);
        $this->assertArrayHasKey('data', $result);
        $this->assertArrayHasKey('notifications', $result);
        $this->assertCount(1, $result['data']);
        $this->assertEquals('Test Subject', $result['data'][0]['subject']);
    }

    /** @test */
    public function it_handles_empty_domain_configuration_gracefully(): void
    {
        Config::set('app.settings.configuration_settings', json_encode([
            'domains' => [],
        ]));

        $zemail = new ZEmail;
        $reflection = new ReflectionClass($zemail);
        $method = $reflection->getMethod('getRandomDomain');

        $result = $method->invoke($zemail);

        $this->assertEquals('', $result);
    }
}
