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

namespace iyixiGames.Application.Services
{
    /// <summary>
    /// 网站数据仓储实现。
    /// </summary>
    public class SiteRepository : ISiteRepository
    {
        private readonly ApplicationDbContext _context;

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

        public async Task<Site?> GetByIdAsync(string id)
        {
            return await _context.Sites
                                 .Include(s => s.TeamMembers)
                                 .Include(s => s.Seo)
                                 .Include(s => s.Analytics)
                                 .Include(s => s.Settings)
                                 .FirstOrDefaultAsync(s => s.Id == id);
        }

        public async Task<IEnumerable<Site>> GetAllAsync()
        {
            return await _context.Sites
                                 .Include(s => s.TeamMembers)
                                 .Include(s => s.Seo)
                                 .Include(s => s.Analytics)
                                 .Include(s => s.Settings)
                                 .ToListAsync();
        }

        public async Task AddAsync(Site site)
        {
            await _context.Sites.AddAsync(site);
            await _context.SaveChangesAsync();
        }

        public async Task UpdateAsync(Site site)
        {
            _context.Sites.Update(site);
            await _context.SaveChangesAsync();
        }

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

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

        public async Task<bool> DomainExistsAsync(string domain)
        {
            return await _context.Sites.AnyAsync(s => s.Domain == domain);
        }
    }
}