<?php

declare(strict_types=1);

namespace Drupal\Tests\conductor\Kernel;

use Drupal\canvas\Entity\Page;
use Drupal\conductor\Hook\ConductorHooks;
use Drupal\conductor\Repository\DraftRepository;
use Drupal\Core\Extension\ThemeInstallerInterface;
use Drupal\KernelTests\KernelTestBase;
use PHPUnit\Framework\Attributes\Group;

/**
 * Tests that ConductorHooks fires correctly via the Drupal hook system.
 */
#[Group("conductor")]
final class ConductorHooksTest extends KernelTestBase {

  protected static $modules = [
    'system',
    'canvas',
    'file',
    'image',
    'link',
    'path',
    'path_alias',
    'media',
    'user',
    'text',
    'options',
    'node',
    'filter',
    'field',
    'editor',
    'ckeditor5',
    'conductor',
    'key',
  ];

  private DraftRepository $draftRepository;

  public function setUp(): void {
    parent::setUp();
    $this->draftRepository = $this->container->get(DraftRepository::class);
    $this->installEntitySchema('user');
    $this->installEntitySchema('canvas_page');
    $this->installEntitySchema('node');
    $this->installEntitySchema('media');
    $this->installSchema('conductor', 'conductor_draft_map');
    $this->container->get(ThemeInstallerInterface::class)->install(['stark']);
    $this->config('system.theme')->set('default', 'stark')->save();
    $this->installConfig(['system', 'conductor', 'canvas', 'key']);
  }

  /**
   * Tests that the entity_delete hook marks a draft mapping as deleted.
   */
  public function testEntityDeleteHookMarksDraftAsDeleted(): void {
    $page = Page::create(['title' => 'Test page', 'status' => TRUE]);
    $page->save();
    \assert($page instanceof Page);

    $entityType = $page->getEntityType()->id();
    $entityId = (int) $page->id();

    $this->draftRepository->createDraft($entityType, $entityId, 'test-draft-id');
    $this->assertNotEmpty($this->draftRepository->getDraft($entityType, $entityId));

    $hooks = $this->container->get(ConductorHooks::class);

    $hooks->entityDelete($page);

    $draft = $this->draftRepository->getDraft($entityType, $entityId);
    $this->assertSame('1', $draft['deleted']);
  }

}
