<?php

declare(strict_types=1);

namespace Drupal\Tests\acquia_dam\Kernel;

use Drupal\acquia_dam\Entity\MediaItemField;
use Drupal\acquia_dam\Entity\MediaSourceField;
use Drupal\acquia_dam\Plugin\Field\FieldType\AssetItem;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\media\Entity\Media;

/**
 * Tests the Asset field when canvas module is enabled.
 *
 * @group acquia_dam_canvas
 * @group acquia_dam_kernel
 */
class AssetFieldTypeWithCanvasTest extends AssetFieldTypeTest {

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'canvas',
    'token',
  ];

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    // We can't call parent::setUp() as it would skip this test for Drupal 11.2+.
    AcquiaDamKernelTestBase::setUp();

    $this->installConfig(['media', 'media_library', 'acquia_dam', 'system', 'canvas']);
    // This is needed because when acquia_dam configuration is imported, it
    // overrides the acquia_dam.settings configuration.
    $this->grantDamDomain();
  }

  /**
   * {@inheritdoc}
   *
   * @covers \Drupal\acquia_dam\Plugin\Field\FieldType\ImageFieldType::propertyDefinitions
   */
  public static function assetFieldDataProvider(): \Generator {
    foreach (parent::assetFieldDataProvider() as $key => $data) {
      // Only modify the image asset.
      if ($key === 'acquia_dam:image') {
        $data['expected_field_properties']['acquia_dam_image_item']['src_with_alternate_widths'] = [
          'getDataType' => 'uri',
          'isReadOnly' => TRUE,
          'isRequired' => FALSE,
          'isComputed' => TRUE,
          'getConstraints' => [
            'UriTargetMediaType' => [
              'mimeType' => 'image/*'
            ],
            'Uri' =>  [
              'allowReferences' => TRUE,
            ],
            'UriScheme' => [
              'http',
              'https',
            ],
            'PrimitiveType' => [],
          ],
          'getClass' => 'Drupal\canvas\Plugin\DataType\ComputedUrlWithQueryString',
        ];
        $data['expected_field_properties']['acquia_dam_image_item']['srcset_candidate_uri_template'] = [
          'getDataType' => 'string',
          'isReadOnly' => TRUE,
          'isRequired' => FALSE,
          'isComputed' => TRUE,
          'getConstraints' => [
            'UriTemplateWithVariables' => [
              'requiredVariables' => ['width'],
            ],
            'PrimitiveType' => [],
          ],
          'getClass' => 'Drupal\acquia_dam\TypedData\AssetDerivativeWithParametrizedWidth',
        ];
      }
      yield $key => $data;
    }
  }


  /**
   * Tests the srcset_candidate_uri_template property for local and remote assets.
   *
   * Ensures that when assets are downloaded locally, the srcset_candidate_uri_template
   * contains the expected local file pattern. When assets are not downloaded,
   * verifies that the property matches the expected remote URL pattern.
   *
   * @covers \Drupal\acquia_dam\TypedData\AssetDerivativeWithParametrizedWidth
   */
  public function testSrcsetCandidateUriTemplateForLocalAndRemoteAssets(): void {
    $media_type = $this->createImageMediaType(['download_assets' => TRUE]);

    $field_definition = $this->container->get('entity_field.manager')
      ->getFieldDefinitions('media', $media_type->id())[MediaSourceField::SOURCE_FIELD_NAME] ?? NULL;
    $this->assertInstanceOf(FieldDefinitionInterface::class, $field_definition, 'The media source field definition should exist.');

    $filename = "wheel-illustration.ai";
    $media = Media::create([
      'name' => $filename,
      'bundle' => $media_type->id(),
      MediaSourceField::SOURCE_FIELD_NAME => AssetItem::generateSampleValue($field_definition),
    ]);
    $media->save();
    $local_image_field = $media->get(MediaItemField::getFieldName('image'))->first();

    $this->assertStringContainsString(
      'files/styles/canvas_parametrized_width--{width}/public/dam',
      $local_image_field->get('srcset_candidate_uri_template')->getValue(),
      'The srcset_candidate_uri_template should contain the expected pattern.'
    );

    $media_type->set('source_configuration', ['download_assets' => FALSE])->save();

    $media = $this->container->get('entity_type.manager')->getStorage('media')->load($media->id());
    $dam_field_value = $media->get(MediaItemField::getFieldName('image'))->first();

    $this->assertMatchesRegularExpression(
      '#^https://test\.widen\.net/content.*\?q=100&w=\{width\}$#',
      $dam_field_value->get('srcset_candidate_uri_template')->getValue(),
      'The srcset_candidate_uri_template should match the expected pattern.'
    );
  }

}
