using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SatelliteProvider.Common.Configs;
using SatelliteProvider.Common.Utils;

namespace SatelliteProvider.Services.RouteManagement;

// AZ-364 / C11: extracted from RouteProcessingService.GenerateRouteCsvAsync.
// Owns the route_<id>_ready.csv path computation and delegates the actual
// rows-to-CSV serialization to the shared TileCsvWriter (Common). Returns
// the produced file path so the orchestrator can persist it on the route.
public class RouteCsvWriter
{
    private readonly StorageConfig _storageConfig;
    private readonly ILogger<RouteCsvWriter> _logger;

    public RouteCsvWriter(IOptions<StorageConfig> storageConfig, ILogger<RouteCsvWriter> logger)
    {
        ArgumentNullException.ThrowIfNull(storageConfig);
        _storageConfig = storageConfig.Value;
        _logger = logger;
    }

    public async Task<string> WriteAsync(
        Guid routeId,
        IEnumerable<TileInfo> tiles,
        CancellationToken cancellationToken = default)
    {
        ArgumentNullException.ThrowIfNull(tiles);

        Directory.CreateDirectory(_storageConfig.ReadyDirectory);
        var filePath = Path.Combine(_storageConfig.ReadyDirectory, $"route_{routeId}_ready.csv");

        var rows = tiles.Select(t => new TileCsvRow(t.Latitude, t.Longitude, t.FilePath)).ToList();
        await new TileCsvWriter().WriteAsync(filePath, rows, cancellationToken);

        _logger.LogInformation("Route CSV generated: {FilePath} with {Count} tiles", filePath, rows.Count);
        return filePath;
    }
}
