<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Services\CotizacionService;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class CotizacionController
{
    private CotizacionService $cotizacionService;

    public function __construct(CotizacionService $cotizacionService)
    {
        $this->cotizacionService = $cotizacionService;
    }

    public function cotizar(Request $request, Response $response): Response
    {
        $body = (array) $request->getParsedBody();

        foreach (['origen_lat', 'origen_lng', 'destino_lat', 'destino_lng'] as $campo) {
            if (!isset($body[$campo]) || !is_numeric($body[$campo])) {
                return $this->json($response, ['error' => "El campo {$campo} es requerido y debe ser numérico"], 422);
            }
        }

        $cotizacion = $this->cotizacionService->cotizar(
            (float) $body['origen_lat'],
            (float) $body['origen_lng'],
            (float) $body['destino_lat'],
            (float) $body['destino_lng']
        );

        return $this->json($response, $cotizacion);
    }

    private function json(Response $response, array $data, int $status = 200): Response
    {
        $response->getBody()->write(json_encode($data));

        return $response->withHeader('Content-Type', 'application/json')->withStatus($status);
    }
}
