<?php
declare(strict_types=1);

/* doc-project | caisse-aqp/public/api/_lib/deliveryCityChoices.php | Réutilise la source de vérité web V1 des communes autorisées par PDV pour la caisse et fournit des helpers partagés de matching/canonicalisation serveur. | Expose: caisseDeliveryCityChoiceMatch, caisseNormalizeDeliveryCityPayload | Dépend de: commande/v1/inc/repo/delivery_city_choices.php | Impacte: validation serveur des adresses client et provisoires côté caisse | Tables: aucune */

require_once __DIR__ . '/../../../../commande/v1/inc/repo/delivery_city_choices.php';

/**
 * @return array{city:string,postal_code:string}|null
 */
function caisseDeliveryCityChoiceMatch(string $storeId, string $city, string $postalCode): ?array
{
    return v1_delivery_city_choice_match($storeId, $city, $postalCode);
}

/**
 * @param array<string,mixed> $payload
 * @return array{ok:bool,payload:array<string,mixed>,error?:string}
 */
function caisseNormalizeDeliveryCityPayload(array $payload, string $storeId, string $cityKey = 'ville', string $postalKey = 'code_postal'): array
{
    $city = array_key_exists($cityKey, $payload) ? (string)$payload[$cityKey] : '';
    $postal = array_key_exists($postalKey, $payload) ? (string)$payload[$postalKey] : '';
    if (trim($city) === '' && trim($postal) === '') {
      return ['ok' => true, 'payload' => $payload];
    }

    $match = caisseDeliveryCityChoiceMatch($storeId, $city, $postal);
    if (!$match) {
      return [
        'ok' => false,
        'payload' => $payload,
        'error' => 'Ville / code postal non autorisés pour ce point de vente.',
      ];
    }

    $payload[$cityKey] = (string)$match['city'];
    $payload[$postalKey] = (string)$match['postal_code'];
    return ['ok' => true, 'payload' => $payload];
}