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

namespace Modules.Library.Database.GatewaysImplementations;

public class LanguageGateway(LanguageRepository repository) : ILanguageGateway
{
    public async Task<List<Application.Models.Language>> GetList()
    {
        var list = await repository.GetAllAsync();
        return list.Select(LanguageConverter.Convert).ToList();
    }

    public async Task<Language> GetLanguageById(Guid id)
    {
        var dbLanguage = await repository.GetByIdAsync(id);
        return LanguageConverter.ConvertToDomain(dbLanguage);
    }

    public async Task<IEnumerable<Language>> GetLanguageByIds(IEnumerable<Guid> languageIds)
    {
        var dbLanguages = await repository.GetWhere(q => languageIds.Contains(q.Id));
        return dbLanguages.Select(LanguageConverter.ConvertToDomain);
    }

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

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

    public async Task Edit(Guid id, string? code, string? name)
    {

        var dbLanguage = await repository.GetByIdAsync(id);
        if (!string.IsNullOrWhiteSpace(code?.Trim())) dbLanguage.CodeIso3 = code.Trim().ToUpper();
        if (!string.IsNullOrWhiteSpace(name?.Trim())) dbLanguage.Name = name.Trim();
        await repository.UpdateAsync();
    }

    public async Task<Language> GetLanguage(string code)
    {
        var dbLanguage = await repository.GetFirstWhere(q => q.CodeIso3 == code);
        return LanguageConverter.ConvertToDomain(dbLanguage);
    }
    

    public Task<bool> IsLanguageExists(string code, string name, Guid? selfId) =>
        repository.AnyWhere(q => q.Id != selfId && (q.CodeIso3 == code.Trim().ToUpper() || q.Name == name.Trim()) && !q.Deleted);



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