<?php

namespace Database\Seeders\Core;

use App\Models\Core\Setting;
use Illuminate\Database\Seeder;
use Illuminate\Support\Str;
use App\Helpers\InstallationLogger;
use Exception;

class SettingsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        InstallationLogger::info('SettingsSeeder: Starting settings seeding');

        try {
            // Check if site_settings config exists
            $siteSettings = config('site_settings');
            if (!$siteSettings) {
                InstallationLogger::error('SettingsSeeder: site_settings config not found');
                throw new Exception('site_settings configuration is missing');
            }

            InstallationLogger::info('SettingsSeeder: Found ' . count($siteSettings) . ' settings in config');

            // Get existing settings to avoid duplicates
            $existingKeys = Setting::pluck('key')->toArray();
            InstallationLogger::info('SettingsSeeder: Found ' . count($existingKeys) . ' existing settings in database');

            $settings = collect($siteSettings)
                ->except($existingKeys)
                ->map(fn(mixed $value, string $key): array => [
                    'uid' => Str::uuid(),
                    'key' => $key,
                    'value' => $value
                ])->values()->all();

            InstallationLogger::info('SettingsSeeder: Will insert ' . count($settings) . ' new settings');

            if (!empty($settings)) {
                Setting::insert($settings);
                InstallationLogger::info('SettingsSeeder: Successfully inserted ' . count($settings) . ' settings');

                // Log sample of inserted settings for verification
                $sampleSettings = array_slice($settings, 0, 5);
                foreach ($sampleSettings as $setting) {
                    InstallationLogger::debug("SettingsSeeder: Inserted setting: {$setting['key']} = {$setting['value']}");
                }
            } else {
                InstallationLogger::info('SettingsSeeder: No new settings to insert (all already exist)');
            }

            // Log some example settings for verification
            $settingCount = Setting::count();
            InstallationLogger::info('SettingsSeeder: Total settings in database after seeding: ' . $settingCount);

            // Verify critical settings exist
            $criticalSettings = ['site_name', 'site_email', 'app_name', 'primary_color', 'secondary_color'];
            foreach ($criticalSettings as $key) {
                $setting = Setting::where('key', $key)->first();
                if ($setting) {
                    InstallationLogger::info("SettingsSeeder: Critical setting '{$key}': EXISTS (value: {$setting->value})");
                } else {
                    InstallationLogger::warning("SettingsSeeder: Critical setting '{$key}': MISSING");
                }
            }

            // Verify all theme colors are properly seeded
            $themeColors = [
                'primary_color',
                'secondary_color',
                'primary_color_text',
                'secondary_color_text',
                'body_text_primary',
                'body_text_secondary'
            ];
            InstallationLogger::info('SettingsSeeder: Theme color verification:');
            foreach ($themeColors as $colorKey) {
                $setting = Setting::where('key', $colorKey)->first();
                if ($setting) {
                    InstallationLogger::info("SettingsSeeder: Theme color '{$colorKey}': {$setting->value}");
                } else {
                    InstallationLogger::error("SettingsSeeder: Theme color '{$colorKey}': MISSING!");
                }
            }

            InstallationLogger::info('SettingsSeeder: Running optimize_clear()');
            optimize_clear();
            InstallationLogger::info('SettingsSeeder: optimize_clear() completed');

        } catch (Exception $e) {
            InstallationLogger::error('SettingsSeeder: Failed with error: ' . $e->getMessage());
            InstallationLogger::error('SettingsSeeder: File: ' . $e->getFile() . ' Line: ' . $e->getLine());
            InstallationLogger::debug('SettingsSeeder: Stack trace: ' . $e->getTraceAsString());
            throw $e;
        }

        InstallationLogger::info('SettingsSeeder: Completed successfully');
    }
}
