<?php
/**
 * Request body builder for Simply.IN parcel locker geolocation API.
 *
 * @package Simplyin\Simplyin_W_Plugin\Service\Geolocation
 */

declare( strict_types=1 );

namespace Simplyin\Simplyin_W_Plugin\Service\Geolocation;

/**
 * Builds JSON body for Simply.IN parcelLockers/getClosest (and compatible endpoints).
 */
final class Closest_Parcel_Lockers_Request_Builder {

	public const KIND_PARCEL_MACHINE = 'parcel_machine';

	public const KIND_SERVICE_POINT = 'service_point';

	/**
	 * @return list<string>
	 */
	public static function allowed_service_types(): array {
		return [
			self::KIND_PARCEL_MACHINE,
			self::KIND_SERVICE_POINT,
		];
	}

	/**
	 * Whitelist API serviceType; empty or unknown values return null (caller omits key — API default / both).
	 *
	 * @param string|null $value Raw POST value or null.
	 * @return string|null One of allowed types or null.
	 */
	public static function normalize_service_type( ?string $value ): ?string {
		if ( null === $value || '' === $value ) {
			return null;
		}
		if ( in_array( $value, self::allowed_service_types(), true ) ) {
			return $value;
		}

		return null;
	}

	/**
	 * @param float                           $lat Latitude.
	 * @param float                           $lng Longitude.
	 * @param int                             $search_radius_meters Radius in meters.
	 * @param int                             $number_of_items Max items (API limit).
	 * @param array<int|string, mixed>|string $accepted_providers Result of Mapping::get_available_providers().
	 * @param string|null                     $service_type parcel_machine, service_point, or null to omit.
	 * @return array<string, mixed>
	 */
	public static function build_body(
		float $lat,
		float $lng,
		int $search_radius_meters,
		int $number_of_items,
		$accepted_providers,
		?string $service_type
	): array {
		$body = [
			'numberOfItemsToFind'           => $number_of_items,
			'searchRadiusInMeters'          => $search_radius_meters,
			'coordinates'                   => [
				'lat' => $lat,
				'lng' => $lng,
			],
			'acceptedParcelLockerProviders' => $accepted_providers,
		];

		$normalized = self::normalize_service_type( $service_type );
		if ( null !== $normalized ) {
			$body['serviceType'] = $normalized;
		}

		return $body;
	}
}
