using iyixiGames.Domain.Entities;
using iyixiGames.Infrastructure.Data;
using iyixiGames.Infrastructure.Services;
using Microsoft.EntityFrameworkCore;

namespace iyixiGames.Application.Services
{
    /// <summary>
    /// 游戏数据仓储实现。
    /// </summary>
    public class GameRepository : IGameRepository
    {
        private readonly ApplicationDbContext _context;

        public GameRepository(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<Game?> GetByIdAsync(string id)
        {
            return await _context.Games.FindAsync(id);
        }

        public async Task<IEnumerable<Game>> GetAllAsync()
        {
            return await _context.Games.ToListAsync();
        }

        public async Task AddAsync(Game game)
        {
            await _context.Games.AddAsync(game);
            await _context.SaveChangesAsync();
        }

        public async Task UpdateAsync(Game game)
        {
            _context.Games.Update(game);
            await _context.SaveChangesAsync();
        }

        public async Task DeleteAsync(string id)
        {
            var game = await _context.Games.FindAsync(id);
            if (game != null)
            {
                _context.Games.Remove(game);
                await _context.SaveChangesAsync();
            }
        }

        public async Task<bool> ExistsAsync(string id)
        {
            return await _context.Games.AnyAsync(g => g.Id == id);
        }

        public async Task<bool> NameExistsAsync(string name)
        {
            return await _context.Games.AnyAsync(g => g.Name == name);
        }
        // 新增：批量添加
        public async Task AddRangeAsync(IEnumerable<Game> games)
        {
            await _context.Games.AddRangeAsync(games);
            await _context.SaveChangesAsync();
        }
        // 新增：检查游戏路径是否已存在
        public async Task<bool> PathExistsAsync(string path)
        {
            return await _context.Games.AnyAsync(g => g.Path == path);
        }
    }
}