<?php

namespace WPML\UserInterface\Web\Core\Component\PostHog\Application\Endpoint\Event\Capture;

use WPML\Core\Component\PostHog\Application\Service\Config\ConfigService;
use WPML\Core\Port\Endpoint\EndpointInterface;
use WPML\PHP\Exception\RemoteException;
use WPML\UserInterface\Web\Core\Port\Remote\RemoteInterface;

class ProxyCaptureEventController implements EndpointInterface {

  /** @var ConfigService */
  private $configService;

  /** @var RemoteInterface */
  private $remote;


  public function __construct(
    ConfigService $configService,
    RemoteInterface $remoteInterface
  ) {
    $this->configService = $configService;
    $this->remote = $remoteInterface;
  }


  /**
   * @psalm-suppress MoreSpecificImplementedParamType
   *
   * @param array{
   *   distinctId: string,
   *   eventName: string,
   *   eventData: array<string, mixed>,
   * }|null $requestData
   *
   * @return array{
   *   success: bool,
   *   message: string,
   * }
   */
  public function handle( $requestData = null ): array {
    if (
      ! is_array( $requestData ) ||
      ! array_key_exists( 'distinctId', $requestData ) ||
      ! array_key_exists( 'eventName', $requestData ) ||
      ! array_key_exists( 'eventData', $requestData )
    ) {
      return [
        'success' => false,
        'message' => 'Invalid request data'
      ];
    }

    try {
      $config = $this->configService->create();

      $host = rtrim( $config->getHost(), '/' ) . '/i/v0/e/';
      $data = [
        'api_key' => $config->getApiKey(),
        'distinct_id' => $requestData['distinctId'],
        'event'   => $requestData['eventName'],
        'properties' => $requestData['eventData'],
        'timestamp' =>  date( 'c' ),
      ];

      $this->remote->post( $host, $data );

    } catch ( RemoteException $e ) {
      return [
        'success' => false,
        'message' => $e->getMessage(),
      ];
    }

    return [
      'success' => true,
      'message' => '',
    ];
  }


}
