using Modules.Library.Domain.Entities.Genre;
using Modules.Library.Application.Gateways;
using Modules.Library.Domain.EntityBuilders;
using Modules.Library.Database.Repositories;
using Modules.Library.Database.GatewaysImplementations.Converters;

namespace Modules.Library.Database.GatewaysImplementations;

public class GenreGateway(GenreRepository repository) : IGenreGateway
{
    
    public async Task<List<Application.Models.Genre>> GetList()
    {
        var list = await repository.GetAllAsync();
        return list.Select(GenreConverter.Convert).ToList();
    }

    public async Task<Genre> GetGenreById(Guid id)
    {
        var dbGenre = await repository.FirstWhereAsync(q => q.Id == id);
        return new GenreBuilder(dbGenre.Name).SetId(dbGenre.Id).Build();
    }
    public async Task<IEnumerable<Genre>> GetGenreByIds(IEnumerable<Guid> genreIds)
    {
        var dbLanguages = await repository.GetWhere(q => genreIds.Contains(q.Id));
        return dbLanguages.Select(GenreConverter.ConvertToDomain);
    }

    public async Task<Guid> Create(string name)
    {
        return await repository.AddAsync(new Database.Models.Genre.Genre
        {
            //Id = genre.Id,
            //Name = genre.Name,
            //Deleted = genre.Deleted,
            Name = name.Trim(),
        });
    }

    public async Task<bool> Delete(Guid id) => await repository.DeleteAsync(id);

    public async Task SetName(Guid id, string name)
    {
        var dbGenre = await repository.FirstWhereAsync(q => q.Id == id && !q.Deleted);
        dbGenre.Name = name.Trim();
        await repository.UpdateAsync();
    }

    public async Task<Genre> GetGenre(string name)
    {
        var dbGenre = await repository.FirstWhereAsync(q => q.Name == name.Trim());
        return GenreConverter.ConvertToDomain(dbGenre);
    }

    public Task<bool> IsGenreExists(Guid id) => repository.AnyWhere(q => q.Id == id && !q.Deleted);

    public Task<bool> IsGenreExists(string name, Guid? selfId) =>
        repository.AnyWhere(q => q.Id != selfId
        && q.Name.ToLower() == name.Trim().ToLower()
        && !q.Deleted);
}