using BBM.ChatGLM.EntityFrameworkCore;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;

namespace BBM.ChatGLM.PromptWord
{
    public class PromptWordsRepository : EfCoreRepository<IChatGLMDbContext, PromptWords, Guid>, IPromptWordsRepository
    {
        public PromptWordsRepository(IDbContextProvider<IChatGLMDbContext> dbContextProvider) : base(dbContextProvider) { }

        public async Task<List<PromptWords>> PageAsync(string filter, string type, int pageSize, int pageIndex, Guid? tenantId)
        {
            return await (await GetDbSetAsync())
                  .WhereIf(!string.IsNullOrWhiteSpace(filter), e => e.Content.Contains(filter))
                  .WhereIf(!string.IsNullOrWhiteSpace(type), e => e.Type == type)
                  .WhereIf(tenantId != null, e => e.TenantId == tenantId)
                  .OrderByDescending(e => e.CreationTime)
                  .PageBy(pageIndex, pageSize)
                  .ToListAsync();
        }

        public async Task<long> CountAsync(string filter, string type, Guid? tenantId)
        {
            return await (await GetDbSetAsync())
                .WhereIf(!string.IsNullOrWhiteSpace(filter), e => e.Content.Contains(filter))
                .WhereIf(!string.IsNullOrWhiteSpace(type), e => e.Type == type)
                .WhereIf(tenantId != null, e => e.TenantId == tenantId)
                .CountAsync();
        }


        public async Task<int> DeleteAsync(Guid id)
        {
            var context = await GetDbContextAsync();
            var entity = await context.PromptWords.FirstOrDefaultAsync(x => x.Id == id);
            entity.IsDeleted = true;
            context.Update(entity);
            return await context.SaveChangesAsync();
        }

        public async Task<PromptWords> UpdateAsync(PromptWords entity)
        {
            var context = await GetDbContextAsync();
            context.Update(entity);
            await context.SaveChangesAsync();
            return entity;
        }
    }
}
