<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media\Form\SettingsTab;

use Drupal\Core\Config\Config;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Drupal\ffmpeg_media\Service\ProfileManagerInterface;

/**
 * Builds the general settings tab for the FFmpeg Media settings form.
 *
 * @internal
 */
final class GeneralSettingsBuilder {

  use StringTranslationTrait;

  /**
   * Constructs a GeneralSettingsBuilder.
   *
   * @param \Drupal\ffmpeg_media\Service\ProfileManagerInterface $profileManager
   *   Profile manager service.
   */
  public function __construct(
    protected readonly ProfileManagerInterface $profileManager,
  ) {
  }

  /**
   * Builds the general section render array.
   *
   * @param array<string, mixed> $form
   *   Form structure, passed by reference.
   * @param \Drupal\Core\Config\Config $config
   *   Module configuration.
   */
  public function build(array &$form, Config $config): void {
    $form['general'] = [
      '#type' => 'details',
      '#title' => $this->t('General'),
      '#description' => $this->t('Core settings: enable/disable the module, configure output storage, file size limits, and original file retention policies.'),
      '#group' => 'settings_tabs',
    ];

    $form['general']['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable FFmpeg Media'),
      '#description' => $this->t('When disabled, no new video conversions will be queued. Existing queued items will finish processing.'),
      '#default_value' => $config->get('enabled'),
    ];

    $profileOptions = [];
    foreach ($this->profileManager->getAllProfiles() as $id => $profile) {
      $profileOptions[$id] = $profile->label;
    }

    $form['general']['default_profile'] = [
      '#type' => 'select',
      '#title' => $this->t('Default profile'),
      '#description' => $this->t('The conversion profile applied when no specific profile is configured for a media type. Manage profiles at <a href=":url">Conversion Profiles</a>.', [
        ':url' => Url::fromRoute('ffmpeg_media.profile_list')->toString(),
      ]),
      '#options' => $profileOptions,
      '#default_value' => $config->get('default_profile'),
      '#required' => TRUE,
    ];

    $form['general']['output_directory'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Output directory'),
      '#description' => $this->t('Where converted video files are stored. Must be a Drupal stream wrapper URI: <em>public://ffmpeg_media</em> for web-accessible files, or <em>private://ffmpeg_media</em> for access-controlled downloads. The directory will be created automatically.'),
      '#default_value' => $config->get('output_directory'),
      '#required' => TRUE,
    ];

    $form['general']['max_file_size'] = [
      '#type' => 'number',
      '#title' => $this->t('Maximum file size (MB)'),
      '#description' => $this->t('Videos larger than this will be rejected. Value is in megabytes (e.g., 500 for 500 MB, 1024 for 1 GB, 2048 for 2 GB).'),
      '#default_value' => (int) ($config->get('max_file_size') / (1024 * 1024)),
      '#min' => 1,
      '#required' => TRUE,
    ];

    $form['general']['preserve_original'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Preserve original files'),
      '#description' => $this->t('Keep original uploaded videos permanently alongside converted versions. Uses more disk space but allows re-conversion with different settings later.'),
      '#default_value' => $config->get('preserve_original'),
    ];

    $form['general']['original_retention'] = [
      '#type' => 'details',
      '#title' => $this->t('Original file retention'),
      '#open' => FALSE,
      '#states' => [
        'visible' => [
          ':input[name="preserve_original"]' => ['checked' => FALSE],
        ],
      ],
    ];

    $form['general']['original_retention']['original_retention_enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable retention'),
      '#description' => $this->t('Automatically remove original files after a retention period.'),
      '#default_value' => $config->get('original_retention_enabled'),
    ];

    $form['general']['original_retention']['original_retention_days'] = [
      '#type' => 'number',
      '#title' => $this->t('Retention period (days)'),
      '#description' => $this->t('How many days the original file should remain available (1-90). Default: 30.'),
      '#default_value' => $config->get('original_retention_days'),
      '#min' => 1,
      '#max' => 90,
      '#states' => [
        'visible' => [
          ':input[name="original_retention_enabled"]' => ['checked' => TRUE],
        ],
      ],
    ];

    $form['general']['original_retention']['original_trash_enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Use trash (safe delete)'),
      '#description' => $this->t('Move original files to a trash directory instead of deleting permanently.'),
      '#default_value' => $config->get('original_trash_enabled'),
    ];

    $form['general']['original_retention']['original_trash_path'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Trash directory'),
      '#description' => $this->t('Directory for trashed originals. Uses private:// if available, otherwise public://ffmpeg_media/trash.'),
      '#default_value' => $config->get('original_trash_path'),
      '#states' => [
        'visible' => [
          ':input[name="original_trash_enabled"]' => ['checked' => TRUE],
        ],
      ],
    ];

    $form['general']['auto_cleanup_failed'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Auto cleanup failed conversions'),
      '#description' => $this->t('Automatically remove incomplete output files when a conversion fails. Prevents accumulation of unusable files on disk.'),
      '#default_value' => $config->get('auto_cleanup_failed'),
    ];

    $form['general']['cleanup_age'] = [
      '#type' => 'number',
      '#title' => $this->t('Cleanup age (seconds)'),
      '#description' => $this->t('Remove permanently failed conversion records older than this age during cron. Default: 86400 (24 hours).'),
      '#default_value' => $config->get('cleanup_age') ?? 86400,
      '#min' => 3600,
      '#step' => 1,
      '#states' => [
        'visible' => [
          ':input[name="auto_cleanup_failed"]' => ['checked' => TRUE],
        ],
      ],
    ];
  }

}
