using Microsoft.EntityFrameworkCore;
using FnbEngine.Domain.AggregatesModel.RecipeAggregate;
using FnbEngine.Domain.SeedWork;

namespace FnbEngine.Infrastructure.Repositories;

public class RecipeRepository : IRecipeRepository
{
    private readonly FnbContext _context;
    public IUnitOfWork UnitOfWork => _context;

    public RecipeRepository(FnbContext context) => _context = context;

    public Recipe Add(Recipe recipe) => _context.Recipes.Add(recipe).Entity;
    public void Update(Recipe recipe) => _context.Recipes.Update(recipe);
    public void Delete(Recipe recipe) => _context.Recipes.Remove(recipe);

    public async Task<Recipe?> GetByIdAsync(Guid id, CancellationToken ct = default) =>
        await _context.Recipes.Include(r => r.Ingredients).FirstOrDefaultAsync(r => r.Id == id, ct);

    public async Task<IEnumerable<Recipe>> GetByShopIdAsync(Guid shopId, CancellationToken ct = default) =>
        await _context.Recipes.Include(r => r.Ingredients)
            .Where(r => r.ShopId == shopId && r.IsActive)
            .OrderBy(r => r.Name)
            .ToListAsync(ct);

    public async Task<Recipe?> GetByProductIdAndShopAsync(Guid productId, Guid shopId, CancellationToken ct = default) =>
        await _context.Recipes.Include(r => r.Ingredients)
            .FirstOrDefaultAsync(r => r.ProductId == productId && r.ShopId == shopId && r.IsActive, ct);
}
