<?php

namespace Limb_Chatbot\Includes\Repositories;

use Exception;
use Limb_Chatbot\Includes\Data_Objects\AI_Model_Meta;


/**
 * Repository class for managing AI_Model_Meta records.
 *
 * @since 1.0.0
 */
class AI_Model_Meta_Repository {

	/**
	 * Creates multiple AI model meta records in batch.
	 *
	 * @param  array  $data  Array of meta data arrays.
	 * @param  int  $ai_model_id  AI model ID to associate metas with.
	 *
	 * @return array Array of created AI_Model_Meta objects.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function batch_create( array $data, int $ai_model_id ): array {
		foreach ( $data as $item ) {
			$metas[] = $this->create( $item + [ 'ai_model_id' => $ai_model_id ] );
		}

		return $metas ?? [];
	}

	/**
	 * Updates multiple AI model meta records in batch.
	 *
	 * Fires a dynamic action hook "{$meta_key}_updated" after each update.
	 * Special handling for fine-tuning process status meta to preserve actual process state.
	 *
	 * @param  array  $data  Array of meta data arrays (must contain 'meta_key' and 'meta_value').
	 * @param  int  $ai_model_id  AI model ID to match records.
	 *
	 * @return array Array of updated AI_Model_Meta objects.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function batch_update( array $data, int $ai_model_id ): array {
		foreach ( $data as $item ) {
			$meta = AI_Model_Meta::update( [ 'ai_model_id' => $ai_model_id, 'meta_key' => $item['meta_key'] ], [ 'meta_value' => $item['meta_value'] ] );
			do_action( "{$item['meta_key']}_updated", $meta );
			$metas[] = $meta;
		}

		return $metas ?? [];
	}

	/**
	 * Creates a single AI_Model_Meta record.
	 *
	 * @param  array  $array  Data to create the meta record.
	 *
	 * @return AI_Model_Meta The created meta record.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function create( array $array ) {
		return AI_Model_Meta::create( $array );
	}

	/**
	 * Deletes AI_Model_Meta records matching given criteria.
	 *
	 * @since 1.0.0
	 *
	 * @param array $array Conditions to delete records.
	 * @return bool Result of delete operation.
	 */
	public function delete( array $array ) {
		return AI_Model_Meta::delete( $array );
	}

	/**
	 * Retrieves AI_Model_Meta records matching given conditions.
	 *
	 * @since 1.0.0
	 *
	 * @param array $array Query conditions.
	 * @return array Collection of meta records.
	 */
	public function get_items( array $array ) {
		return AI_Model_Meta::where( $array )->get();
	}

	/**
	 * Updates AI_Model_Meta records matching conditions with new data.
	 *
	 * @param  array  $where  Conditions to find records.
	 * @param  array  $update_data  Data to update records with.
	 *
	 * @return AI_Model_Meta Result of update operation.
	 * @throws Exception
	 * @since 1.0.0
	 */
	public function update( array $where, array $update_data ) {
		return AI_Model_Meta::update( $where, $update_data );
	}
}