<?php

declare(strict_types=1);

namespace Drupal\ffmpeg_media\Form\SettingsTab;

use Drupal\Core\Config\Config;
use Drupal\Core\StringTranslation\StringTranslationTrait;

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

  use StringTranslationTrait;

  /**
   * Builds the advanced 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['advanced'] = [
      '#type' => 'details',
      '#title' => $this->t('Advanced'),
      '#description' => $this->t('Stuck process detection, automatic requeuing, and other maintenance settings.'),
      '#group' => 'settings_tabs',
      '#open' => FALSE,
    ];

    $form['advanced']['stuck_process_timeout'] = [
      '#type' => 'number',
      '#title' => $this->t('Stuck process timeout (seconds)'),
      '#description' => $this->t('If a conversion has not reported progress for this long, it is considered stuck. This can happen after server restarts or crashes.'),
      '#default_value' => $config->get('stuck_process_timeout'),
      '#min' => 600,
      '#max' => 86400,
      '#required' => TRUE,
    ];

    $form['advanced']['stuck_auto_requeue'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Auto-requeue stuck processes'),
      '#description' => $this->t('Automatically requeue stuck conversions so they are retried. When disabled, stuck conversions must be requeued manually via Drush.'),
      '#default_value' => $config->get('stuck_auto_requeue'),
    ];

    $form['advanced']['auto_requeue_batch_limit'] = [
      '#type' => 'number',
      '#title' => $this->t('Auto-requeue batch limit'),
      '#description' => $this->t('Maximum number of stuck conversions to requeue per cron run. Prevents a single cron cycle from flooding the queue.'),
      '#default_value' => $config->get('auto_requeue_batch_limit') ?? 25,
      '#min' => 1,
      '#max' => 500,
      '#required' => TRUE,
      '#states' => [
        'visible' => [
          ':input[name="stuck_auto_requeue"]' => ['checked' => TRUE],
        ],
      ],
    ];

    $form['advanced']['segment_cleanup_age'] = [
      '#type' => 'number',
      '#title' => $this->t('Segment cleanup age (seconds)'),
      '#description' => $this->t('Age in seconds after which orphaned streaming segments and temporary files are cleaned up during cron. Default: 86400 (24 hours).'),
      '#default_value' => $config->get('segment_cleanup_age') ?? 86400,
      '#min' => 3600,
      '#max' => 604800,
      '#required' => TRUE,
    ];
  }

}
