<?php

namespace Drupal\dc_core\Drush\Commands;

use Drush\Commands\DrushCommands;
use Drush\Attributes as CLI;

final class CharacterImport extends DrushCommands {

  /**
   * Imports characters from Lord of the Rings.
   */
  #[CLI\Command(name: 'lotr:character-import', aliases: ['lotr-i'])]
  #[CLI\Usage(name: 'drush lotr-i', description: 'Adds update operations to queue for import.')]
  public function importCharacters(): void {
    $http_client = \Drupal::httpClient();
    $character_endpoint = "https://dchadwick.ddev.site/api/character-list";
    $data = $http_client->get($character_endpoint, ['verify'=>FALSE,])->getBody()->getContents();
    $json_data = json_decode($data, TRUE);
    // Create the queue.
    $character_import_queue = \Drupal::queue('character_import');

    foreach ($json_data as $id => $api_character) {
      // Load corresponding Drupal entity, check last modified.
      $properties = [
        'field_character_id' => $id,
      ];

      $drupal_entity = \Drupal::entityTypeManager()
        ->getStorage('node')
        ->loadByProperties($properties);

      if (empty($drupal_entity)) {
        $character = new \stdClass();
        $character->id = $id;
        $character->operation = "CREATE";
        $character_import_queue->createItem($character);
      }
      else {
        $drupal_entity = reset($drupal_entity);
        $changed = $drupal_entity->getChangedTime();
        if ($changed < $api_character['last_modified']) {
          $character = new \stdClass();
          $character->id = $id;
          $character->operation = "UPDATE";
          $character_import_queue->createItem($character);
        };
      }
    }
  }

}
