<?php
declare(strict_types=1);

namespace Celena\Module\Ai;

use Celena\Core\Http\Request;
use Celena\Core\Http\Response;
use Celena\Core\Security\Auth;
use Celena\Core\Security\Csrf;
use Celena\Core\Security\Filter;
use Celena\Core\Security\Permission;
use Celena\Core\Template\Engine;
use Celena\Module\AdminBase\AdminController;
use Celena\Module\Settings\Options;

final class AiSettingsController extends AdminController
{
    public function __construct(Engine $engine, Auth $auth, Options $options)
    {
        parent::__construct($engine, $auth, $options);
    }

    public function index(Request $request): Response
    {
        if (!Permission::can($this->auth->user(), 'options.read')) {
            return $this->redirect('/admin', 'Доступ запрещён.', 'error');
        }
        return $this->view('admin/ai/index', [
            'ai' => [
                'provider'        => (string) $this->options->get('ai_provider', 'anthropic'),
                'anthropic_key'   => $this->mask((string) $this->options->get('ai_anthropic_key', '')),
                'anthropic_model' => (string) $this->options->get('ai_anthropic_model', 'claude-sonnet-4-6'),
                'openai_key'      => $this->mask((string) $this->options->get('ai_openai_key', '')),
                'openai_model'    => (string) $this->options->get('ai_openai_model', 'gpt-4o-mini'),
            ],
        ], 'ai-settings', 'ИИ-интеграция');
    }

    public function save(Request $request): Response
    {
        if (!Permission::can($this->auth->user(), 'options.write')) {
            return $this->redirect('/admin', 'Доступ запрещён.', 'error');
        }
        if (!Csrf::validate((string) $request->input('_csrf'))) {
            return $this->redirect('/admin/ai-settings', 'CSRF.', 'error');
        }
        $this->options->set('ai_provider', Filter::in($request->input('provider'), ['anthropic', 'openai'], 'anthropic'));

        foreach (['anthropic', 'openai'] as $p) {
            $key = (string) $request->input($p . '_key', '');
            // Не перезаписываем ключ пустым/маской — сохраняем старый
            if ($key !== '' && !str_contains($key, '•')) {
                $this->options->set('ai_' . $p . '_key', $key);
            }
            $model = Filter::string($request->input($p . '_model', ''), 128);
            if ($model !== '') {
                $this->options->set('ai_' . $p . '_model', $model);
            }
        }
        return $this->redirect('/admin/ai-settings', 'Настройки ИИ сохранены.');
    }

    private function mask(string $key): string
    {
        if ($key === '') return '';
        $len = strlen($key);
        return $len > 8 ? substr($key, 0, 4) . str_repeat('•', 6) . substr($key, -4) : str_repeat('•', $len);
    }
}
