<?php

namespace Limb_Chatbot\Includes\Repositories;

use Limb_Chatbot\Includes\Data_Objects\Config;
use Limb_Chatbot\Includes\Services\Collection;


/**
 * Repository class for managing Config data objects.
 *
 * Handles creation, updating, and retrieval of Config records.
 *
 * @since 1.0.0
 */
class Config_Repository {

	/**
	 * Creates a new configuration record.
	 *
	 * Encrypts the API key before storing it.
	 *
	 * @param  array  $data  Configuration data.
	 *
	 * @return Config The created Config instance.
	 * @throws \Exception
	 * @since 1.0.0
	 *
	 */
	public function create( array $data ): Config {
		$config = Config::make( $data );
		$config->encrypt_params();
		$config->save();

		return $config;
	}

	/**
	 * Updates an existing configuration record by ID.
	 *
	 * Encrypts the API key before updating.
	 *
	 * @since 1.0.0
	 *
	 * @param int   $config_id Configuration ID.
	 * @param array $data      Updated configuration data.
	 * @return Config The updated Config instance.
	 */
	public function update( $config_id, array $data ): Config {
		$config = Config::find( $config_id );
		if(isset($data['params'])) {
			$config->params = $data['params'];
		}
		if(isset($data['title'])) {
			$config->title = $data['title'];
		}
		if(isset($data['description'])) {
			$config->description = $data['description'];
		}
		if(isset($data['related_to'])) {
			$config->related_to = $data['related_to'];
		}
		if(isset($data['default'])) {
			$config->default = $data['default'];
		}

		$config->encrypt_params();
		return $config->save();
	}

	/**
	 * Retrieves a collection of configuration records matching given parameters.
	 *
	 * Supports search with partial match via LIKE queries.
	 *
	 * @since 1.0.0
	 *
	 * @param array $params Query parameters (supports 'search', 'search_fields', 'per_page', 'page', 'orderby', 'order').
	 * @return Collection A collection of Config instances.
	 */
	public function get_items( $params ): Collection {
		if ( ! empty( $params['search'] ) && ! empty( $params['search_fields'] ) ) {
			foreach ( $params['search_fields'] as $field ) {
				$params["{$field}LIKE"] = "%{$params['search']}%";
			}
		}

		return Config::where( $params, $params['per_page'] ?? 10, $params['page'] ?? 1, $params['orderby'] ?? 'created_at', $params['order'] ?? 'DESC' );
	}
}