using DomainResults.Common;

using DataProviders.Collections;

using Core.Abstractions;
using Core.Enumerations;

using WeatherForecast.Models.Responses;


namespace WeatherForecast.Services {

  /// <summary>
  /// 
  /// </summary>
  public interface ICategoryItemsService {

    /// <summary>
    /// 
    /// </summary>
    /// <param name="siteId"></param>
    /// <param name="locale"></param>
    /// <returns></returns>
    (List<CategoryItemResponseModel>?, IDomainResult) Get(Guid siteId, string? locale);

    /// <summary>
    /// 
    /// </summary>
    /// <param name="siteId"></param>
    /// <returns></returns>
    IDomainResult Delete(Guid siteId);
  }

  /// <summary>
  /// 
  /// </summary>
  public class CategoryItemsService : ServiceBase<CategoryItemsService>, ICategoryItemsService {

    private readonly ICategoryDataProvider _categoryDataProvider;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="logger"></param>
    /// <param name="categoryDataProvider"></param>
    public CategoryItemsService(
      ILogger<CategoryItemsService> logger,
      ICategoryDataProvider categoryDataProvider
    ) : base(logger) {
      _categoryDataProvider = categoryDataProvider;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="siteId"></param>
    /// <param name="locale"></param>
    /// <returns></returns>
    public (List<CategoryItemResponseModel>?, IDomainResult) Get(Guid siteId, string? locale) {
      try {
        var (items, result) = _categoryDataProvider.GetAll(siteId);
        if (!result.IsSuccess || items == null)
          return (null, result);

        if (locale != null) {
          return IDomainResult.Success(items.Select(x => new CategoryItemResponseModel(x, Enumeration.FromDisplayName<Locales>(locale) ?? Locales.Us)).ToList());
        }

        return IDomainResult.Success(items.Select(x => new CategoryItemResponseModel(x)).ToList());
      }
      catch (Exception ex) {
        _logger.LogError(ex, "Unhandled exception");
        return IDomainResult.Failed<List<CategoryItemResponseModel>?>(ex.Message);
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="siteId"></param>
    /// <returns></returns>
    public IDomainResult Delete(Guid siteId) {
      try {
        return _categoryDataProvider.DeleteAll(siteId);
      }
      catch (Exception ex) {
        _logger.LogError(ex, "Unhandled exception");
        return IDomainResult.Failed(ex.Message);
      }
    }
  }
}
