<?php

declare(strict_types=1);

namespace App\ValueObject;

final readonly class Distance
{
    private const int EARTH_RADIUS_KM = 6371;

    private function __construct(
        private float $kilometers,
    ) {
    }

    public static function between(Point $from, Point $to): self
    {
        $lat1 = deg2rad($from->getLat());
        $lat2 = deg2rad($to->getLat());
        $deltaLat = deg2rad($to->getLat() - $from->getLat());
        $deltaLng = deg2rad($to->getLng() - $from->getLng());

        $haversine = sin($deltaLat / 2) ** 2 + cos($lat1) * cos($lat2) * sin($deltaLng / 2) ** 2;
        $centralAngle = 2 * atan2(sqrt($haversine), sqrt(1 - $haversine));

        return new self(self::EARTH_RADIUS_KM * $centralAngle);
    }

    public function inKilometers(): float
    {
        return $this->kilometers;
    }

    public function inMeters(): float
    {
        return $this->kilometers * 1000;
    }
}
