<?php

namespace Drupal\api_monitor_client\Form;

use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

/**
 * Form controller for the api_monitor_manual entity edit forms.
 */
class ApiMonitorManualForm extends ContentEntityForm {

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ?Request $request = NULL) {
    $form = parent::buildForm($form, $form_state);

    // Pre-populate provider from URL parameter when coming from provider list.
    if ($this->entity->isNew() && $request && $request->query->has('provider')) {
      $provider_id = $request->query->get('provider');
      $provider = $this->entityTypeManager->getStorage('api_monitor_provider')->load($provider_id);
      if ($provider) {
        $form['provider']['widget'][0]['target_id']['#value'] = $provider->label() . ' (' . $provider_id . ')';
      }
    }

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state): int {
    $result = parent::save($form, $form_state);

    $message = $result === SAVED_NEW
      ? $this->t('Created the %label manual endpoint.', ['%label' => $this->entity->label()])
      : $this->t('Updated the %label manual endpoint.', ['%label' => $this->entity->label()]);

    $this->messenger()->addStatus($message);
    $form_state->setRedirect('entity.api_monitor_manual.collection');

    return $result;
  }

}
