<?php

declare(strict_types=1);

namespace Drupal\Tests\conductor\Kernel;

use Drupal\canvas\Entity\Page;
use Drupal\conductor\DraftCleanup;
use Drupal\Core\Extension\ThemeInstallerInterface;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\conductor\Trait\DraftTrait;
use Drupal\Tests\conductor\Trait\KeyTrait;
use PHPUnit\Framework\Attributes\Group;

/**
 * Draft cleanup test.
 */
#[Group("conductor")]
final class DraftCleanupTest extends KernelTestBase {

  use DraftTrait;
  use KeyTrait;

  private DraftCleanup $draftCleanup;

  private Page $page;

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'system',
    'canvas',
    'file',
    'image',
    'link',
    'path',
    'path_alias',
    'media',
    'user',
    'text',
    'options',
    'node',
    'filter',
    'field',
    'editor',
    'ckeditor5',
    'conductor',
    'conductor_test',
    'http_request_mock',
    'key',
  ];

  public function setUp(): void {
    parent::setUp();
    $this->draftCleanup = $this->container->get(DraftCleanup::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', 'conductor_test', 'canvas', 'key']);

    $this->page = Page::create([
      'title' => 'asdf',
      'status' => TRUE,
    ]);
    $this->page->save();
  }

  public function testCleanupSkippedWhenDisabled(): void {
    // By default, enable_draft_cleanup is FALSE; no drafts should be deleted.
    $this->generateKey();
    $this->createHistoricalDraft(2025);
    $this->createHistoricalDraft(2025);

    $draftsDeleted = $this->draftCleanup->run();
    $this->assertCount(0, $draftsDeleted);
  }

  public function testCleanupDrafts(): void {
    $this->config('conductor.settings')->set('enable_draft_cleanup', TRUE)->save();
    $this->generateKey();
    $this->createHistoricalDraft(2025);
    $this->createHistoricalDraft(2025);
    // @see `fixtures/api/get-drafts-200.json`
    // Create a draft with a title "Untitled Canvas draft:", but linked to an entity
    // This draft MUST NOT BE DELETED
    $this->createHistoricalDraft(2025, '061cdaf2-7957-4c44-a116-0431291c1712');

    $draftsDeleted = $this->draftCleanup->run();
    // According to `fixtures/api/get-drafts-200.json` we only have one
    // draft, unlinked, with title starting `Untitled Canvas draft:`.
    $this->assertCount(1, $draftsDeleted);
    $this->assertSame('084452b3-0138-4837-ae7d-67dc455bd324', $draftsDeleted[0]);
  }

}
