<?php

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Config;
use App\Core\Controller;
use App\Core\Database;
use App\Core\Database\Migrator;
use App\Services\ImageService;
use App\Services\OpenAIService;

class SettingsController extends Controller
{
    private array $settingKeys = [
        'openai_api_key',
        'openai_model',
        'freepik_api_key',
        'unsplash_api_key',
        'pexels_api_key',
        'image_provider',
        'article_min_words',
        'article_max_words',
        'article_generation_prompt',
        'internal_linking_enabled',
        'internal_link_min_count',
        'internal_link_max_count',
        'openai_embedding_model',
        'image_generation_prompt',
        'semstorm_login',
        'semstorm_password',
        'semstorm_api_base',
        'semstorm_timeout_seconds',
        'dataforseo_login',
        'dataforseo_password',
        'dataforseo_api_base',
        'dataforseo_timeout_seconds',
        'dataforseo_location_code',
        'dataforseo_language_code',
    ];

    private array $settingDefaults = [
        'openai_model' => 'gpt-4o',
        'image_provider' => 'freepik',
        'article_min_words' => '900',
        'article_max_words' => '1400',
        'article_generation_prompt' => OpenAIService::DEFAULT_ARTICLE_PROMPT_TEMPLATE,
        'internal_linking_enabled' => '1',
        'internal_link_min_count' => '2',
        'internal_link_max_count' => '4',
        'openai_embedding_model' => 'text-embedding-3-small',
        'image_generation_prompt' => ImageService::DEFAULT_FREEPIK_PROMPT_TEMPLATE,
        'semstorm_api_base' => 'https://api.semstorm.com',
        'semstorm_timeout_seconds' => '30',
        'dataforseo_api_base' => 'https://api.dataforseo.com',
        'dataforseo_timeout_seconds' => '30',
        'dataforseo_location_code' => '2616',
        'dataforseo_language_code' => 'pl',
    ];

    public function index(): void
    {
        Auth::requireLogin();

        $settings = [];
        foreach ($this->settingKeys as $key) {
            $settings[$key] = Config::getDbSetting($key, $this->settingDefaults[$key] ?? '');
        }

        $this->view('settings/index', ['settings' => $settings]);
    }

    public function update(): void
    {
        Auth::requireLogin();

        foreach ($this->settingKeys as $key) {
            $value = $this->input($key);
            if ($value !== null) {
                Config::setDbSetting($key, $value);
            }
        }

        Config::clearCache();

        $this->flash('success', 'Ustawienia zostały zapisane.');
        $this->redirect('/settings');
    }

    public function database(): void
    {
        Auth::requireLogin();

        $migrator = new Migrator(
            Database::getInstance(),
            dirname(__DIR__, 2) . '/migrations'
        );

        $status = $migrator->status();
        $runLogs = $_SESSION['migration_logs'] ?? null;
        unset($_SESSION['migration_logs']);

        $this->view('settings/database', [
            'status' => $status,
            'runLogs' => $runLogs,
        ]);
    }

    public function migrate(): void
    {
        Auth::requireLogin();

        $migrator = new Migrator(
            Database::getInstance(),
            dirname(__DIR__, 2) . '/migrations'
        );

        try {
            $result = $migrator->runPending();
            $_SESSION['migration_logs'] = $result['logs'];

            if ($result['executed'] > 0) {
                $this->flash('success', "Wykonano {$result['executed']} migracji.");
            } else {
                $this->flash('info', 'Brak oczekujacych migracji.');
            }
        } catch (\Throwable $e) {
            $this->flash('danger', 'Blad migracji: ' . $e->getMessage());
        }

        $this->redirect('/settings/database');
    }
}
