using Microsoft.EntityFrameworkCore;
using Modules.Library.Database.Database;
using Modules.Library.Database.Database.Models.Language;
using System.Linq.Expressions;

namespace Modules.Library.Database.Repositories;

//public class LanguageRepository(LibraryDbContext context) : RepositoryBase<Language>(context)
public class LanguageRepository(LibraryDbContext context)
{
    private readonly LibraryDbContext _context = context;
    public async Task<Language> GetLanguage(string code) =>
        await _context.Languages.FirstAsync(q => q.CodeIso3 == code);

    internal async Task<IEnumerable<Language>> GetAllAsync() => await _context.Languages.ToListAsync();

    internal async Task<Guid> AddAsync(Language language)
    {
        if (await AnyWhere(q => q.CodeIso3 == language.CodeIso3.Trim().ToUpper() &&
            q.Name.ToLower() == language.Name.Trim().ToLower())) throw new Exception("Language is laready exists");
        _context.Languages.Add(language);
        await _context.SaveChangesAsync();
        return language.Id;
    }

    internal async Task<bool> AnyWhere(Expression<Func<Language, bool>> predicate) =>
        await _context.Languages.AnyAsync(predicate);


    internal async Task<List<Language>> GetWhere(Expression<Func<Language, bool>> predicate) =>
        await _context.Languages.Where(predicate).ToListAsync();

    internal async Task<Language> GetByIdAsync(Guid languageId) =>
        await _context.Languages.FirstAsync(q => q.Id == languageId);

    internal async Task<bool> DeleteAsync(Guid languageId)
    {
        var language = await _context.Languages.FirstAsync(q => q.Id == languageId && !q.Deleted);
        if (language == null) return false;
        language.Deleted = true;
        await _context.SaveChangesAsync();
        return true;
    }

    internal async Task UpdateAsync() => await _context.SaveChangesAsync();

    internal async Task<Language> GetFirstWhere(Expression<Func<Language, bool>> predicate) =>
        await _context.Languages.FirstAsync(predicate);
}