<?php
$_db_migration_to = '42.01'; // 11.0.0-beta
if (!isset($migrations) || !is_object($migrations))
	die("This file cannot be executed directly");
$migrations->CheckValid($_db_migration_to);
//===========================================================================================



$migrations->Run('202601271134_add_vector_storage_table.php', <<<'DB_UPDATE_FILE'
<?php

/**
 * FRAM-1099
 * 
 * This merge request adds a new table: `indexing_vector_cache`.
 * 
 * This new table is responsible for storing cached vector embeddings to reduce the amount of calls
 * made to the AI API server.
 */

use Claromentis\Core\DAL;

/** @var \Claromentis\Setup\SetupFacade $migrations */
$logger = $migrations->getLogger();

$logger->notice("Starting migration for FRAM-1099");

$database = $migrations->GetDb();

try {
    $columns = [
        'type' => 'VARCHAR(100) NULL',
        'content_hash' => 'VARCHAR(64) NULL',
        'content' => 'CLOB NULL',
        'embeddings' => 'CLOB NULL',
        'processing' => 'BOOL DEFAULT 0',
        'date_accessed' => 'INT_DATE NOT_NULL'
    ];

    $database->CreateTable('indexing_vector_cache', $columns);
    $database->CreateIndex('indexing_vector_cache', 'indexing_vector_cache_type_content_hash_index', 'type', 'content_hash');
    $database->CreateIndex('indexing_vector_cache', 'indexing_vector_cache_type_content_hash_processing', 'type', 'content_hash', 'processing');

} catch (DAL\Exceptions\TransactionException $exception) {
    $logger->error("Migration failed for FRAM-1099");

    // Rethrow the exception to ensure the migration and upgrade fails
    throw $exception;
}
DB_UPDATE_FILE
);


//===========================================================================================
$migrations->SetVersion('42.01');
