<?php
require_once APPPATH . 'libraries/Cf_REST_Controller.php';

class SettingsApi extends Cf_REST_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('vcsSettingsModel');
        $this->load->model('llmConfigModel');
        $this->load->model('settings_rest_model');
        $this->settings_rest_model->setRestClient($this->getRestClient());
    }

    public function clearVCS_post()
    {
        try {
            $this->vcsSettingsModel->deleteSettings();
            $this->respond(204);
        } catch (Exception $e) {
            $message = $e->getMessage();
            log_message('error', $message);
            $this->respond(500, $message);
        }
    }

    public function LLMConfig_post()
    {
        $data = json_decode($this->request->body, true);
        $this->llmConfigModel->createConfig($data);
        $this->respond(201);
    }

    public function LLMConfig_put($id)
    {
        $data = json_decode($this->_put_args, true);
        $this->llmConfigModel->updateConfig($id, $data);
        $this->respond(201);
    }

    public function LLMConfig_get()
    {
        $config = $this->llmConfigModel->getFirstConfig();
        if (isset($config['token']) && !empty($config['token'])) {
            $config['token'] = '';
            $config['isTokenSet'] = true;
        }
        $this->respond(200, json_encode($config));
    }

    public function LLMConfig_delete($id)
    {
        $this->llmConfigModel->deleteConfig($id);
        $this->respond(204);
    }

    public function preferences_put()
    {
        $data = json_decode($this->_put_args, true);
        $this->settings_rest_model->updateData($data);
        $this->respond(204);
    }

    public function preferences_get()
    {
        $preferences = $this->settings_rest_model->get_app_settings();
        $this->respond(200, json_encode($preferences));
    }
}
