<?php

declare(strict_types=1);

namespace Drupal\Tests\acquia_dam\Kernel;

use Drupal\Core\Url;

/**
 * Tests AcquiaDamMetadataConfigurationForm (V1 metadata API path).
 *
 * @group acquia_dam_kernel
 */
final class AcquiaDamMetadataConfigurationFormTest extends AcquiaDamKernelTestBase {

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();
  }

  /**
   * Tests that the metadata config form loads and renders V1 fields.
   *
   * The MockedResponseMiddleware intercepts the V1 API call
   * (GET /api/rest/metadata/types) and returns metadata-fields-v1.json.
   * The form should render a tableselect containing those field labels.
   */
  public function testFormLoadsV1MetadataFields(): void {
    $this->drupalSetUpCurrentUser([], [], TRUE);

    $url = Url::fromRoute('acquia_dam.metadata_config')->toString();
    $request  = $this->getMockedRequest($url, 'GET');
    $response = $this->processRequest($request);

    self::assertEquals(200, $response->getStatusCode());

    $content = (string) $response->getContent();
    // Fields from the V1 fixture must appear as table rows.
    self::assertStringContainsString('Asset Type',      $content);
    self::assertStringContainsString('Description',     $content);
    self::assertStringContainsString('Keywords',        $content);
    self::assertStringContainsString('Image Type',      $content);
    self::assertStringContainsString('Usage Rights',    $content);
  }

  /**
   * Tests that submitting the form persists the selected fields to config.
   *
   * Only checked (non-zero) checkboxes should appear in allowed_metadata.
   * Unchecked fields must not be saved.
   */
  public function testFormSubmitSavesAllowedMetadata(): void {
    $this->drupalSetUpCurrentUser([], [], TRUE);

    // Load the form to obtain the CSRF/build tokens required for submission.
    $url = Url::fromRoute('acquia_dam.metadata_config')->toString();
    $this->processRequest($this->getMockedRequest($url, 'GET'));

    $data = [
      'metadata' => [
        'asset_type'  => 'asset_type',
        'description' => 'description',
      ],
    ];

    // Submit the form. The third argument must match ConfigFormBase's button
    // label exactly; the default 'Save' does not trigger submitForm().
    $response = $this->doFormSubmit(
      $url,
      $data,
      'Save configuration'
    );

    // The form redirects (303) on success.
    self::assertContains($response->getStatusCode(), [200, 303]);

    $allowed = $this->config('acquia_dam.settings')->get('allowed_metadata');
    self::assertIsArray($allowed);
    self::assertArrayHasKey('asset_type',  $allowed, 'asset_type should be saved.');
    self::assertArrayHasKey('description', $allowed, 'description should be saved.');
    self::assertArrayNotHasKey('keywords', $allowed, 'Unchecked field must not be saved.');
  }

}

