<?php

namespace Modules\ProductCompat\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Modules\ProductCompat\Entities\Services\Settings;

class SettingsController extends Controller
{
    /** Keys exposed in the settings form. */
    protected array $keys = [
        'icecat_username', 'icecat_lang',
        'searxng_url', 'searxng_delay_ms', 'google_cse_key', 'google_cse_cx', 'serp_key',
        'enrich_batch_size', 'auto_enrich_enabled', 'auto_enrich_frequency', 'auto_enrich_target',
        // AI enrichment queue
        'ai_queue_enabled', 'ai_queue_frequency', 'ai_queue_batch_size', 'ai_queue_max_attempts',
        'ai_auto_queue_on_create', 'ai_extra_search', 'ai_image_max_kb', 'ai_provider_enabled',
        'ai_use_model_knowledge', 'ai_require_searxng',
        'ai_queue_auto_seed', 'ai_queue_auto_seed_cap',
    ];

    public function edit()
    {
        if (! auth()->user()->can('productcompat.review')) {
            abort(403, 'Unauthorized action.');
        }

        $s = [];
        foreach ($this->keys as $k) {
            $s[$k] = Settings::get($k);
        }
        // sensible defaults
        $s['icecat_username']       = $s['icecat_username'] ?: config('productcompat.enrichment.icecat.username');
        $s['icecat_lang']           = $s['icecat_lang'] ?: 'en';
        $s['enrich_batch_size']     = $s['enrich_batch_size'] ?: 400;
        $s['auto_enrich_frequency'] = $s['auto_enrich_frequency'] ?: 'hourly';
        $s['auto_enrich_target']    = $s['auto_enrich_target'] ?: 'enrich_has';

        // AI enrichment queue defaults.
        $s['ai_queue_frequency']    = $s['ai_queue_frequency'] ?: 'hourly';
        $s['ai_queue_batch_size']   = $s['ai_queue_batch_size'] ?: 10;
        $s['ai_queue_max_attempts'] = $s['ai_queue_max_attempts'] ?: 3;
        $s['ai_image_max_kb']       = $s['ai_image_max_kb'] ?: 2048;
        // Booleans: default ON for auto-queue-on-create + extra-search, OFF for the rest.
        $s['ai_queue_enabled']        = \Modules\ProductCompat\Entities\Services\Settings::bool('ai_queue_enabled', false);
        $s['ai_auto_queue_on_create'] = \Modules\ProductCompat\Entities\Services\Settings::bool('ai_auto_queue_on_create', true);
        $s['ai_extra_search']         = \Modules\ProductCompat\Entities\Services\Settings::bool('ai_extra_search', true);
        $s['ai_provider_enabled']     = \Modules\ProductCompat\Entities\Services\Settings::bool('ai_provider_enabled', false);
        $s['ai_use_model_knowledge']  = \Modules\ProductCompat\Entities\Services\Settings::bool('ai_use_model_knowledge', false);
        $s['ai_require_searxng']      = \Modules\ProductCompat\Entities\Services\Settings::bool('ai_require_searxng', false);
        $s['ai_queue_auto_seed']      = \Modules\ProductCompat\Entities\Services\Settings::bool('ai_queue_auto_seed', false);
        $s['ai_queue_auto_seed_cap']  = $s['ai_queue_auto_seed_cap'] ?: 500;

        // Last queue-run telemetry (confirms the cron is firing).
        $s['ai_queue_last_run_at']      = Settings::get('ai_queue_last_run_at');
        $s['ai_queue_last_scheduled_at'] = Settings::get('ai_queue_last_scheduled_at');
        $s['ai_queue_last_run_trigger'] = Settings::get('ai_queue_last_run_trigger');
        $s['ai_queue_last_run_outcome'] = Settings::get('ai_queue_last_run_outcome');
        $s['ai_queue_last_run_note']    = Settings::get('ai_queue_last_run_note');

        // AiCore availability for the status indicator.
        $aiAvailable = false;
        if (class_exists(\Modules\ProductCompat\Entities\Services\AiExtractionService::class)) {
            $aiAvailable = (new \Modules\ProductCompat\Entities\Services\AiExtractionService())
                ->available((int) session('user.business_id'));
        }
        $s['ai_available'] = $aiAvailable;

        $limitAt  = Settings::get('icecat_limit_reached_at');
        $limitMsg = Settings::get('icecat_limit_message');

        return view('productcompat::settings.edit', compact('s', 'limitAt', 'limitMsg'));
    }

    public function save(Request $request)
    {
        if (! auth()->user()->can('productcompat.review')) {
            abort(403, 'Unauthorized action.');
        }

        Settings::set('icecat_username', trim((string) $request->input('icecat_username')));
        Settings::set('icecat_lang', trim((string) $request->input('icecat_lang')) ?: 'en');
        Settings::set('searxng_url', rtrim(trim((string) $request->input('searxng_url')), '/'));
        Settings::set('searxng_delay_ms', max(0, (int) $request->input('searxng_delay_ms', 0)));
        Settings::set('google_cse_key', trim((string) $request->input('google_cse_key')));
        Settings::set('google_cse_cx', trim((string) $request->input('google_cse_cx')));
        Settings::set('serp_key', trim((string) $request->input('serp_key')));
        Settings::set('enrich_batch_size', (int) $request->input('enrich_batch_size', 400));
        Settings::set('auto_enrich_enabled', $request->boolean('auto_enrich_enabled') ? '1' : '0');
        Settings::set('auto_enrich_frequency', $request->input('auto_enrich_frequency', 'hourly'));
        Settings::set('auto_enrich_target', $request->input('auto_enrich_target', 'enrich_has'));

        // AI enrichment queue.
        Settings::set('ai_queue_enabled', $request->boolean('ai_queue_enabled') ? '1' : '0');
        Settings::set('ai_queue_frequency', $request->input('ai_queue_frequency', 'hourly'));
        Settings::set('ai_queue_batch_size', max(1, (int) $request->input('ai_queue_batch_size', 10)));
        Settings::set('ai_queue_max_attempts', max(1, (int) $request->input('ai_queue_max_attempts', 3)));
        Settings::set('ai_auto_queue_on_create', $request->boolean('ai_auto_queue_on_create') ? '1' : '0');
        Settings::set('ai_extra_search', $request->boolean('ai_extra_search') ? '1' : '0');
        Settings::set('ai_image_max_kb', max(1, (int) $request->input('ai_image_max_kb', 2048)));
        Settings::set('ai_provider_enabled', $request->boolean('ai_provider_enabled') ? '1' : '0');
        Settings::set('ai_use_model_knowledge', $request->boolean('ai_use_model_knowledge') ? '1' : '0');
        Settings::set('ai_require_searxng', $request->boolean('ai_require_searxng') ? '1' : '0');
        Settings::set('ai_queue_auto_seed', $request->boolean('ai_queue_auto_seed') ? '1' : '0');
        Settings::set('ai_queue_auto_seed_cap', max(1, (int) $request->input('ai_queue_auto_seed_cap', 500)));

        // Changing the account clears the limit flag.
        Settings::set('icecat_limit_reached_at', '');
        Settings::set('icecat_limit_message', '');

        return redirect()->back()->with('status', ['success' => 1, 'msg' => 'Settings saved.']);
    }
}
