namespace SatelliteProvider.Services.RouteManagement.TileProvision;

public sealed record ClientTileSnapshot(
    int Z,
    int X,
    int Y,
    double ResolutionMetersPerPx,
    DateTime CapturedAtUtc,
    byte[]? ContentSha256);

public static class ClientTileCatalog
{
    public static Dictionary<(int Z, int X, int Y), ClientTileSnapshot> IndexByZxy(
        IEnumerable<ClientTileSnapshot> clientTiles)
    {
        var index = new Dictionary<(int Z, int X, int Y), ClientTileSnapshot>();
        foreach (var tile in clientTiles)
        {
            index[(tile.Z, tile.X, tile.Y)] = tile;
        }

        return index;
    }

    public static bool ShouldSkipForClient(
        ClientTileSnapshot? client,
        ServerTileProspect server)
    {
        if (client is null)
        {
            return false;
        }

        if (client.ContentSha256 is { Length: 32 } clientHash
            && server.ContentSha256 is { Length: 32 } serverHash
            && clientHash.AsSpan().SequenceEqual(serverHash))
        {
            return true;
        }

        if (client.ResolutionMetersPerPx <= server.ResolutionMetersPerPx
            && client.CapturedAtUtc >= server.CapturedAtUtc)
        {
            return true;
        }

        return false;
    }
}
