<?php

namespace Drupal\languagewire_translation_provider\Adapter\Database;

use Drupal\Core\Database\Connection;
use Drupal\languagewire_translation_provider\Adapter\TMGMT\TmgmtTranslatorInterface;
use Drupal\languagewire_translation_provider\Database\TablesInterface;

/**
 * Drupal Configuration Item Repository.
 */
final class ConfigurationItemRepository implements LanguageWireConfigurationItemRepositoryInterface {
  /**
   * Database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  private Connection $connection;

  /**
   * Constructs a new ConfigurationItemRepository object.
   *
   * @param \Drupal\Core\Database\Connection $connection
   *   Database connection.
   */
  public function __construct(Connection $connection) {
    $this->connection = $connection;
  }

  /**
   * {@inheritDoc}
   *
   * @throws \Exception
   */
  public function removeAll(TmgmtTranslatorInterface $translator, string $itemType): void {
    $this->connection->delete(TablesInterface::CONFIGURATION_ITEM)
      ->condition('type', $itemType)
      ->condition('translator_id', $translator->id())
      ->execute();
  }

  /**
   * {@inheritDoc}
   *
   * @throws \Exception
   */
  public function saveAll(array $items, TmgmtTranslatorInterface $translator, string $itemType): void {
    $insertQuery = $this->connection->insert(TablesInterface::CONFIGURATION_ITEM)
      ->fields(['item_id', 'name', 'type', 'translator_id']);

    foreach ($items as $item) {
      $insertQuery->values([
        'item_id' => $item->id(),
        'name' => $item->name(),
        'type' => $itemType,
        'translator_id' => $translator->id(),
      ]);
    }

    $insertQuery->execute();
  }

  /**
   * {@inheritDoc}
   *
   * @throws \Exception
   */
  public function getAll(TmgmtTranslatorInterface $translator, string $itemType): array {
    return $this->connection->select(TablesInterface::CONFIGURATION_ITEM, 'item')
      ->fields('item')
      ->condition('type', $itemType)
      ->condition('translator_id', $translator->id())
      ->execute()
      ->fetchAll();
  }

  /**
   * {@inheritDoc}
   *
   * @throws \Exception
   */
  public function getByIdAndType(TmgmtTranslatorInterface $translator, int $itemId, string $itemType): ?\stdClass {
    $item = $this->connection->select(TablesInterface::CONFIGURATION_ITEM, 'item')
      ->fields('item')
      ->condition('type', $itemType)
      ->condition('translator_id', $translator->id())
      ->condition('item_id', $itemId)
      ->execute()
      ->fetchObject();

    return is_object($item) ? $item : NULL;
  }

}
