using AsbCloudApp.Repositories;
using AsbCloudDb.Model;
using Mapster;
using Microsoft.Extensions.Caching.Memory;
using System.Collections.Generic;
using System.Linq;
using AsbCloudApp.Data.WellOperation;

namespace AsbCloudInfrastructure.Repository;

public class WellOperationCategoryRepository : IWellOperationCategoryRepository
{
    private readonly IAsbCloudDbContext db;
    private readonly IMemoryCache memoryCache;

    public WellOperationCategoryRepository(IAsbCloudDbContext db, IMemoryCache memoryCache)
    {
        this.db = db;
        this.memoryCache = memoryCache;
    }

    public IEnumerable<WellOperationCategoryDto> Get(bool includeParents, bool includeHidden = true)
    {
        var categories = memoryCache
            .GetOrCreateBasic(db.Set<WellOperationCategory>());

        if (!includeHidden)
            categories = categories.Where(o => o.IsHidden == false);

        if (!includeParents)
        {
            var parentIds = categories
                .Select(o => o.IdParent)
                .Distinct();

            categories = categories
                .Where(o => !parentIds.Contains(o.Id));
        }

        var result = categories
            .OrderBy(o => o.Name)
            .Adapt<IEnumerable<WellOperationCategoryDto>>();

        return result;
    }
}