<?php declare(strict_types = 1);

namespace MailPoet\CustomFields\RestApi\Endpoints;

if (!defined('ABSPATH')) exit;


use InvalidArgumentException;
use MailPoet\API\REST\Request;
use MailPoet\API\REST\Response;
use MailPoet\CustomFields\ApiDataSanitizer;
use MailPoet\CustomFields\CustomFieldsRepository;
use MailPoet\CustomFields\RestApi\CustomFieldApiException;
use MailPoet\Entities\CustomFieldEntity;
use MailPoet\Validator\Builder;
use MailPoetVendor\Doctrine\DBAL\Exception\UniqueConstraintViolationException;

class CustomFieldsPostEndpoint extends CustomFieldsEndpoint {
  /** @var CustomFieldsRepository */
  private $customFieldsRepository;

  /** @var ApiDataSanitizer */
  private $apiDataSanitizer;

  public function __construct(
    CustomFieldsRepository $customFieldsRepository,
    ApiDataSanitizer $apiDataSanitizer
  ) {
    $this->customFieldsRepository = $customFieldsRepository;
    $this->apiDataSanitizer = $apiDataSanitizer;
  }

  public function handle(Request $request): Response {
    try {
      $data = $this->apiDataSanitizer->sanitize($this->getRequestData($request));
    } catch (InvalidArgumentException $exception) {
      throw new CustomFieldApiException(
        $exception->getMessage(),
        400,
        'mailpoet_custom_fields_invalid_data',
        [],
        $exception
      );
    }

    $existing = $this->customFieldsRepository->findOneBy(['name' => $data['name']]);
    if ($existing instanceof CustomFieldEntity) {
      throw new CustomFieldApiException(
        __('A custom field with this name already exists.', 'mailpoet'),
        409,
        'mailpoet_custom_fields_duplicate'
      );
    }

    try {
      $customField = $this->customFieldsRepository->createOrUpdate($data);
    } catch (UniqueConstraintViolationException $exception) {
      // Concurrent request created a field with the same name between the duplicate-name check and the insert.
      throw new CustomFieldApiException(
        __('A custom field with this name already exists.', 'mailpoet'),
        409,
        'mailpoet_custom_fields_duplicate',
        [],
        $exception
      );
    }
    return new Response($this->buildItem($customField), 201);
  }

  /**
   * @return array{name: string, type: string, params: array}
   */
  private function getRequestData(Request $request): array {
    $rawName = $request->getParam('name');
    $rawType = $request->getParam('type');
    $rawParams = $request->getParam('params');
    return [
      'name' => sanitize_text_field(is_scalar($rawName) ? (string)$rawName : ''),
      'type' => sanitize_key(is_scalar($rawType) ? (string)$rawType : ''),
      'params' => is_array($rawParams) ? $this->sanitizeParams($rawParams) : [],
    ];
  }

  private function sanitizeParams(array $params): array {
    $sanitized = [];
    foreach ($params as $key => $value) {
      if (is_array($value)) {
        $sanitized[$key] = $this->sanitizeParams($value);
      } elseif (is_scalar($value)) {
        $sanitized[$key] = sanitize_text_field((string)$value);
      }
    }
    return $sanitized;
  }

  public static function getRequestSchema(): array {
    return [
      'name' => Builder::string()->required()->minLength(1),
      'type' => Builder::string()->required()->minLength(1),
      'params' => Builder::object(),
    ];
  }
}
