using BBM.ChatGLM.EntityFrameworkCore;
using BBM.ChatGLM.PromptWordType.Aggregates;
using BBM.ChatGLM.PromptWordType.Repositorys;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;

namespace BBM.ChatGLM.PromptWordType
{
    public class PromptWordTypeRepository : EfCoreRepository<IChatGLMDbContext, PromptWordTypes, Guid>, IPromptWordTypeRepository
    {
        public PromptWordTypeRepository(IDbContextProvider<IChatGLMDbContext> dbContextProvider) : base(dbContextProvider) { }

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

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


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

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