using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using StorageService.Domain.AggregatesModel.FileAggregate;
using StorageService.Infrastructure.Configuration;

namespace StorageService.Infrastructure.CDN;

/// <summary>
/// EN: CDN service implementation for generating CDN URLs.
/// VI: Implementation CDN service để tạo CDN URLs.
/// </summary>
public class CDNService : ICDNService
{
    private readonly CDNSettings _settings;
    private readonly ILogger<CDNService> _logger;

    public CDNService(
        IOptions<CDNSettings> settings,
        ILogger<CDNService> logger)
    {
        _settings = settings.Value;
        _logger = logger;
    }

    /// <inheritdoc />
    public bool IsEnabled => _settings.Enabled && !string.IsNullOrEmpty(_settings.BaseUrl);

    /// <inheritdoc />
    public string? GetCDNUrl(string objectKey, FileAccessLevel accessLevel)
    {
        // EN: CDN only applies to public files
        // VI: CDN chỉ áp dụng cho public files
        if (!IsEnabled)
        {
            _logger.LogDebug("CDN is disabled, returning null");
            return null;
        }

        if (accessLevel != FileAccessLevel.Public)
        {
            _logger.LogDebug("CDN not applicable for {AccessLevel} files", accessLevel);
            return null;
        }

        // EN: Generate CDN URL by combining base URL with object key
        // VI: Tạo CDN URL bằng cách kết hợp base URL với object key
        var cdnUrl = CombineUrl(_settings.BaseUrl, objectKey);
        
        _logger.LogDebug("Generated CDN URL: {Url} for object: {ObjectKey}", cdnUrl, objectKey);
        return cdnUrl;
    }

    /// <inheritdoc />
    public CDNUrlResult? GetCDNUrlWithCacheInfo(string objectKey, FileAccessLevel accessLevel, string contentType)
    {
        var url = GetCDNUrl(objectKey, accessLevel);
        
        if (url == null)
            return null;

        var cacheTtl = _settings.GetCacheTtl(contentType);
        var cacheControl = $"public, max-age={cacheTtl}";

        return new CDNUrlResult(url, cacheTtl, cacheControl);
    }

    /// <summary>
    /// EN: Combine base URL with path.
    /// VI: Kết hợp base URL với path.
    /// </summary>
    private static string CombineUrl(string baseUrl, string path)
    {
        var trimmedBase = baseUrl.TrimEnd('/');
        var trimmedPath = path.TrimStart('/');
        return $"{trimmedBase}/{trimmedPath}";
    }
}
