using DomainResults.Common;

using DataProviders.Collections;

using WeatherForecast.Models.Responses;
using Core.Abstractions;

namespace WeatherForecast.Services {

  /// <summary>
  /// 
  /// </summary>
  public interface IContentService {

    /// <summary>
    /// 
    /// </summary>
    /// <param name="siteId"></param>
    /// <param name="locale"></param>
    /// <returns></returns>
    (ContentResponseModel?, IDomainResult) GetContent(Guid siteId, string locale);
  }

  /// <summary>
  /// 
  /// </summary>
  public class ContentService : ServiceBase<ContentService>, IContentService {

    private readonly IContentDataProvider _contentDataProvider;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="logger"></param>
    /// <param name="contentDataprovider"></param>
    public ContentService(
      ILogger<ContentService> logger,
      IContentDataProvider contentDataprovider
    ) : base(logger) {
      _contentDataProvider = contentDataprovider;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="siteId"></param>
    /// <param name="locale"></param>
    /// <returns></returns>
    public (ContentResponseModel?, IDomainResult) GetContent(Guid siteId, string locale) {
      try {
        var (content, result) = _contentDataProvider.Get(siteId);
        if (!result.IsSuccess || content == null)
          return (null, result);

        return IDomainResult.Success(new ContentResponseModel(content.Single(x => x.Localization.Locale == locale)));
      }
      catch (Exception ex) {
        _logger.LogError(ex, "Unhandled exception");
        return IDomainResult.Failed<ContentResponseModel?>(ex.Message);
      }
    }
  }
}
