using HoneyBox.Core.Interfaces;
using HoneyBox.Model.Data;
using Microsoft.EntityFrameworkCore;

namespace HoneyBox.Core.Services;

/// <summary>
/// 基础服务实现类
/// </summary>
/// <typeparam name="TEntity">实体类型</typeparam>
/// <typeparam name="TKey">主键类型</typeparam>
public abstract class BaseService<TEntity, TKey> : IBaseService<TEntity, TKey> where TEntity : class
{
    protected readonly HoneyBoxDbContext _dbContext;
    protected readonly DbSet<TEntity> _dbSet;

    protected BaseService(HoneyBoxDbContext dbContext)
    {
        _dbContext = dbContext;
        _dbSet = dbContext.Set<TEntity>();
    }

    /// <inheritdoc/>
    public virtual async Task<TEntity?> GetByIdAsync(TKey id)
    {
        return await _dbSet.FindAsync(id);
    }

    /// <inheritdoc/>
    public virtual async Task<IEnumerable<TEntity>> GetAllAsync()
    {
        return await _dbSet.ToListAsync();
    }

    /// <inheritdoc/>
    public virtual async Task<TEntity> AddAsync(TEntity entity)
    {
        await _dbSet.AddAsync(entity);
        await _dbContext.SaveChangesAsync();
        return entity;
    }

    /// <inheritdoc/>
    public virtual async Task<bool> UpdateAsync(TEntity entity)
    {
        _dbSet.Update(entity);
        return await _dbContext.SaveChangesAsync() > 0;
    }

    /// <inheritdoc/>
    public virtual async Task<bool> DeleteAsync(TKey id)
    {
        var entity = await GetByIdAsync(id);
        if (entity == null)
            return false;

        _dbSet.Remove(entity);
        return await _dbContext.SaveChangesAsync() > 0;
    }
}
