using Lactose.Context;
using Lactose.Models;

namespace Lactose.Repositories;

public class AlbumRepository(LactoseDbContext context) : IAlbumRepository {
    public void Insert(Album album) => context.Albums.Add(album);

    public void Update(Album album) {
        album.UpdatedAt = DateTime.Now;
        context.Albums.Update(album);
    }

    public void UpdateBulk(IEnumerable<Album> albums) {
        foreach (var album in albums) {
            album.UpdatedAt = DateTime.Now;
            context.Albums.Update(album);
        }
    }

    public IEnumerable<Album> SearchQuery(string query, int page = 0, int pageSize = 150) {
        return context.Albums
            .Where(x => x.Title.Contains(query))
            .Skip(page * pageSize)
            .Take(pageSize);
    }
    
    public void Save() => context.SaveChanges();

    public Album? Find(Guid id) => context.Albums.Find(id);

    public IEnumerable<Album> FindByOwner(Guid ownerId) => context.Albums.Where(a => a.UserOwnerId == ownerId);
    
    public IEnumerable<Album> FindByPerson(Guid personId) => context.Albums.Where(a => a.PersonOwnerId == personId);

    public IEnumerable<Album> FindBulk(IEnumerable<Guid> ids) => context.Albums.Where(a => ids.Contains(a.Id));

    public IEnumerable<Album> FindByDateRange(DateTime from, DateTime to)
        => context.Albums.Where(x => x.CreatedAt >= from && x.UpdatedAt <= to);

    public void Remove(Album album) => context.Albums.Remove(album);
    
    public void Dispose() => context.Dispose();
}
