<?php

declare(strict_types=1);

namespace Drupal\flowdrop_memory;

use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\Sql\SqlContentEntityStorageSchema;

/**
 * Defines the storage schema for FlowDrop memory records.
 *
 * Adds composite indexes to the base table to support efficient lookups
 * by the memory backend:
 *
 * - memory_scope_lookup: exact key lookup by (scope, scope_id, memory_key)
 * - memory_scope_index:  list all keys in a scope (scope, scope_id)
 * - memory_expiry_index: TTL expiry sweeps (expires)
 *
 * memory_key uses a 191-character prefix in indexes because it is defined as
 * VARCHAR(512) which exceeds the safe single-column index limit for utf8mb4
 * on older MySQL/MariaDB versions.
 *
 * @internal
 */
class MemoryRecordStorageSchema extends SqlContentEntityStorageSchema {

  /**
   * {@inheritdoc}
   */
  protected function getEntitySchema(ContentEntityTypeInterface $entity_type, $reset = FALSE): array {
    $schema = parent::getEntitySchema($entity_type, $reset);

    $base_table = $this->storage->getBaseTable();
    $schema[$base_table]['indexes'] += [
      'memory_scope_lookup' => ['scope', 'scope_id', ['memory_key', 191]],
      'memory_scope_index'  => ['scope', 'scope_id'],
      'memory_expiry_index' => ['expires'],
    ];

    return $schema;
  }

}
