<?php

namespace App\Models;

use CodeIgniter\Model;

class TransportDistanceCacheModel extends Model
{
    protected $table         = 'transport_distance_cache';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;

    protected $allowedFields = [
        'origin_lat', 'origin_lng', 'dest_lat', 'dest_lng',
        'distance_km', 'duration_minutes', 'provider', 'fetched_at',
    ];

    /**
     * Coordinates are rounded to 4 decimals (~11m) so nearby lookups share cache rows.
     */
    public static function roundCoord(float $value): string
    {
        return number_format($value, 4, '.', '');
    }

    public function lookup(float $originLat, float $originLng, float $destLat, float $destLng): ?array
    {
        return $this->where([
            'origin_lat' => self::roundCoord($originLat),
            'origin_lng' => self::roundCoord($originLng),
            'dest_lat'   => self::roundCoord($destLat),
            'dest_lng'   => self::roundCoord($destLng),
        ])->first();
    }

    public function store(float $originLat, float $originLng, float $destLat, float $destLng, float $distanceKm, float $durationMinutes, string $provider): void
    {
        $data = [
            'origin_lat'       => self::roundCoord($originLat),
            'origin_lng'       => self::roundCoord($originLng),
            'dest_lat'         => self::roundCoord($destLat),
            'dest_lng'         => self::roundCoord($destLng),
            'distance_km'      => round($distanceKm, 3),
            'duration_minutes' => round($durationMinutes, 2),
            'provider'         => $provider,
            'fetched_at'       => date('Y-m-d H:i:s'),
        ];

        // Unique key on the coordinate pair: upsert so refreshed values win.
        $this->db->table($this->table)->replace($data);
    }
}
