<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class NewSettingsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->command->info('Seeding new settings system...');

        // Clear only the settings groups we're about to insert
        DB::table('db_config')->whereIn('group', ['website', 'imap', 'configuration'])->delete();

        // Website Settings (based on WebsiteSettings.php)
        $websiteSettings = [
            'app_name' => 'ZEmailnator',
            'app_version' => '1.0',
            'app_base_url' => 'https://zemailnator.test',
            'app_admin' => config('app.admin_email', 'admin@zemail.me'),
            'app_contact' => 'support@zemail.me',
            'app_title' => 'ZEmailnator - Temporary Email Service',
            'app_description' => 'Free temporary email service for protecting your privacy',
            'app_keyword' => 'temporary email, disposable email, fake email',
            'app_meta' => [
                'author' => 'ZEmailnator',
                'version' => '1.0',
                'generator' => 'ZEmailnator v1.0',
            ],
            'app_social' => [
                ['icon' => 'fab-twitter', 'url' => 'https://twitter.com/zemailnator'],
                ['icon' => 'fab-github', 'url' => 'https://github.com/zemailnator'],
                ['icon' => 'fab-discord', 'url' => 'https://discord.gg/zemailnator'],
            ],
            'app_header' => '',
            'app_footer' => '',
            'ads_settings' => [
                'one' => '',
                'two' => '',
                'three' => '',
                'four' => '',
                'five' => '',
            ],
        ];

        // IMAP Settings (based on ImapSettings.php)
        $imapSettings = [
            'public' => [
                'host' => 'test.com',
                'port' => '587',
                'encryption' => 'ssl',
                'validate_cert' => false,
                'username' => 'user',
                'password' => 'pass',
                'default_account' => 'default',
                'protocol' => 'imap',
                'cc_check' => false,
            ],
            'premium' => [
                'host' => 'imap.gmail.com',
                'port' => '993',
                'encryption' => 'ssl',
                'validate_cert' => true,
                'username' => 'premium@yourdomain.com',
                'password' => 'premium-app-password',
                'default_account' => 'default',
                'protocol' => 'imap',
                'cc_check' => true,
            ],
        ];

        // Configuration Settings (based on ConfigurationSettings.php)
        $configurationSettings = [
            'enable_masking_external_link' => true,
            'disable_mailbox_slug' => false,
            'enable_create_from_url' => true,
            'enable_ad_block_detector' => true,
            'font_family' => [
                'head' => 'Poppins',
                'body' => 'Inter',
            ],
            'default_language' => 'en',
            'add_mail_in_title' => false,
            'disable_used_email' => false,
            'fetch_seconds' => 15,
            'email_limit' => 10,
            'fetch_messages_limit' => 15,
            'cron_password' => Str::random(20),
            'date_format' => 'd M Y h:i A',
            'custom_username_length_min' => 3,
            'custom_username_length_max' => 20,
            'random_username_length_min' => 6,
            'random_username_length_max' => 12,
            'after_last_email_delete' => 'redirect_to_homepage',
            'forbidden_ids' => [
                ['forbidden_id' => 'admin'],
                ['forbidden_id' => 'root'],
                ['forbidden_id' => 'test'],
                ['forbidden_id' => 'api'],
                ['forbidden_id' => 'mail'],
                ['forbidden_id' => 'support'],
                ['forbidden_id' => 'noreply'],
                ['forbidden_id' => 'info'],
            ],
            'blocked_domains' => [
                ['blocked_domain' => 'spam.com'],
                ['blocked_domain' => 'malware.net'],
                ['blocked_domain' => 'phishing.site'],
                ['blocked_domain' => 'blocked.com'],
            ],
        ];

        // Insert settings into db_config table
        $this->seedWebsiteSettings($websiteSettings);
        $this->seedImapSettings($imapSettings);
        $this->seedConfigurationSettings($configurationSettings);

        $this->command->info('✅ New settings system seeded successfully!');
        $this->command->info('📧 Website: '.count($websiteSettings).' settings');
        $this->command->info('🔧 IMAP: '.count($imapSettings['public']) + count($imapSettings['premium']).' settings');
        $this->command->info('⚙️ Configuration: '.count($configurationSettings).' settings');
    }

    /**
     * Seed website settings.
     */
    private function seedWebsiteSettings(array $settings): void
    {
        foreach ($settings as $key => $value) {
            $this->insertSetting('website', $key, $value);
        }
    }

    /**
     * Seed IMAP settings.
     */
    private function seedImapSettings(array $settings): void
    {
        foreach ($settings as $key => $value) {
            $this->insertSetting('imap', $key, $value);
        }
    }

    /**
     * Seed configuration settings.
     */
    private function seedConfigurationSettings(array $settings): void
    {
        foreach ($settings as $key => $value) {
            $this->insertSetting('configuration', $key, $value);
        }
    }

    /**
     * Insert a single setting using raw SQL.
     */
    private function insertSetting(string $group, string $key, $value): void
    {
        // Always JSON encode to satisfy the JSON_VALID constraint
        $encodedValue = json_encode($value);
        $now = now()->toDateTimeString();

        // Use raw SQL for insert
        DB::statement(
            'INSERT INTO `db_config` (`group`, `key`, `settings`, `created_at`, `updated_at`)
             VALUES (?, ?, ?, ?, ?)',
            [$group, $key, $encodedValue, $now, $now]
        );
    }
}
