<?php

namespace Core\App\Models;

use PDO;

class GeminiSettingModel
{
    protected PDO $db;

    public function __construct()
    {
        $this->db = db();
    }

    public function get(): ?array
    {
        $stmt = $this->db->prepare("
            SELECT * FROM ai_settings
            WHERE provider = 'gemini'
            LIMIT 1
        ");
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        return $row ?: null;
    }

    public function save(string $apiKey, int $enabled, string $dialect, string $model): void
    {
        $exists = $this->get();

        $dialect = $dialect ?: 'fusha';
        $model   = $model ?: 'models/gemini-2.0-flash';

        if ($exists) {
            $stmt = $this->db->prepare("
                UPDATE ai_settings SET
                    api_key = :api_key,
                    is_active = :is_active,
                    dialect = :dialect,
                    model = :model
                WHERE provider = 'gemini'
            ");
        } else {
            $stmt = $this->db->prepare("
                INSERT INTO ai_settings
                (provider, api_key, is_active, dialect, model)
                VALUES
                ('gemini', :api_key, :is_active, :dialect, :model)
            ");
        }

        $stmt->execute([
            ':api_key'   => $apiKey,
            ':is_active' => $enabled,
            ':dialect'   => $dialect,
            ':model'     => $model,
        ]);
    }
}
