using iyixiGames.Domain.DTOs.Sites;
using iyixiGames.Domain.Entities;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using iyixiGames.Domain.DTOs.Sites;
using iyixiGames.Infrastructure.Services;

namespace iyixiGames.Application.Services
{
    /// <summary>
    /// 网站管理的应用服务实现。
    /// 负责网站的创建、读取、更新、删除等业务逻辑。
    /// </summary>
    public class SiteService : ISiteService
    {
        private readonly ISiteRepository _siteRepository;
        private readonly ILogger<SiteService> _logger;

        public SiteService(ISiteRepository siteRepository, ILogger<SiteService> logger)
        {
            _siteRepository = siteRepository;
            _logger = logger;
        }

        /// <summary>
        /// 根据ID获取网站详情。
        /// </summary>
        /// <param name="id">网站ID。</param>
        /// <returns>网站响应DTO，如果未找到则为null。</returns>
        public async Task<SiteResponse?> GetSiteByIdAsync(string id)
        {
            _logger.LogInformation("尝试获取网站，ID: {SiteId}", id);
            var site = await _siteRepository.GetByIdAsync(id);
            if (site == null)
            {
                _logger.LogWarning("未找到网站，ID: {SiteId}", id);
                return null;
            }
            return MapToSiteResponse(site);
        }

        /// <summary>
        /// 获取所有网站列表。
        /// </summary>
        /// <returns>所有网站的响应DTO列表。</returns>
        public async Task<IEnumerable<SiteResponse>> GetAllSitesAsync()
        {
            _logger.LogInformation("尝试获取所有网站列表。");
            var sites = await _siteRepository.GetAllAsync();
            return sites.Select(MapToSiteResponse).ToList();
        }

        /// <summary>
        /// 创建新网站。
        /// </summary>
        /// <param name="request">创建网站的请求数据。</param>
        /// <returns>新创建网站的响应DTO。</returns>
        /// <exception cref="InvalidOperationException">当域名已存在时抛出。</exception>
        public async Task<SiteResponse> CreateSiteAsync(CreateSiteRequest request)
        {
            _logger.LogInformation("尝试创建新网站，名称: {SiteName}, 域名: {SiteDomain}", request.Name, request.Domain);

            if (await _siteRepository.DomainExistsAsync(request.Domain))
            {
                _logger.LogWarning("创建网站失败：域名 '{SiteDomain}' 已存在。", request.Domain);
                throw new InvalidOperationException($"域名 '{request.Domain}' 已存在。");
            }

            var site = new Site
            {
                Name = request.Name,
                Domain = request.Domain,
                OwnerUserId = request.OwnerUserId,
                Status = "active", // 默认新创建网站为激活状态
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            // 处理团队成员
            if (request.TeamMembers != null && request.TeamMembers.Any())
            {
                site.TeamMembers = request.TeamMembers.Select(tm => new SiteTeamMember
                {
                    UserId = tm.UserId,
                    Role = tm.Role
                }).ToList();
            }

            // 处理 SEO 信息
            if (request.Seo != null)
            {
                site.Seo = new SiteSeo
                {
                    Description = request.Seo.Description,
                    Keywords = request.Seo.Keywords
                };
            }

            // 处理设置
            if (request.Settings != null)
            {
                site.Settings = new SiteSettings
                {
                    Theme = request.Settings.Theme,
                    Language = request.Settings.Language,
                    AdEnabled = request.Settings.AdEnabled
                };
            }

            await _siteRepository.AddAsync(site);
            _logger.LogInformation("网站 '{SiteName}' (ID: {SiteId}) 创建成功。", site.Name, site.Id);
            return MapToSiteResponse(site);
        }

        /// <summary>
        /// 更新现有网站信息。
        /// </summary>
        /// <param name="id">要更新的网站ID。</param>
        /// <param name="request">更新网站的请求数据。</param>
        /// <returns>更新后网站的响应DTO，如果网站不存在则为null。</returns>
        /// <exception cref="InvalidOperationException">当更新后的域名已存在（且不属于当前网站）时抛出。</exception>
        public async Task<SiteResponse?> UpdateSiteAsync(string id, UpdateSiteRequest request)
        {
            _logger.LogInformation("尝试更新网站，ID: {SiteId}", id);
            var site = await _siteRepository.GetByIdAsync(id);
            if (site == null)
            {
                _logger.LogWarning("更新网站失败：未找到网站，ID: {SiteId}", id);
                return null; // 网站不存在
            }

            // 检查域名是否冲突
            if (!string.IsNullOrEmpty(request.Domain) && request.Domain != site.Domain)
            {
                if (await _siteRepository.DomainExistsAsync(request.Domain))
                {
                    _logger.LogWarning("更新网站失败：域名 '{SiteDomain}' 已存在且不属于当前网站。", request.Domain);
                    throw new InvalidOperationException($"域名 '{request.Domain}' 已被其他网站使用。");
                }
                site.Domain = request.Domain;
            }

            // 更新基本信息
            if (!string.IsNullOrEmpty(request.Name)) site.Name = request.Name;
            if (!string.IsNullOrEmpty(request.OwnerUserId)) site.OwnerUserId = request.OwnerUserId;
            site.UpdatedAt = DateTime.UtcNow;

            // 更新团队成员（这里采取替换策略，根据实际业务需求可调整为增量更新）
            if (request.TeamMembers != null)
            {
                site.TeamMembers.Clear(); // 清除现有成员
                foreach (var tmDto in request.TeamMembers)
                {
                    site.TeamMembers.Add(new SiteTeamMember { UserId = tmDto.UserId, Role = tmDto.Role });
                }
            }

            // 更新 SEO
            if (request.Seo != null)
            {
                if (site.Seo == null) site.Seo = new SiteSeo();
                site.Seo.Description = request.Seo.Description;
                site.Seo.Keywords = request.Seo.Keywords;
            }
            else if (site.Seo != null && request.Seo == null)
            {
                site.Seo = null; // 如果请求中移除了SEO信息，则清除
            }


            // 更新设置
            if (request.Settings != null)
            {
                if (site.Settings == null) site.Settings = new SiteSettings();
                site.Settings.Theme = request.Settings.Theme;
                site.Settings.Language = request.Settings.Language;
                site.Settings.AdEnabled = request.Settings.AdEnabled;
            }
            else if (site.Settings != null && request.Settings == null)
            {
                site.Settings = null; // 如果请求中移除了设置信息，则清除
            }

            // Analytics 不在此处更新，通常由后台任务或数据导入更新

            await _siteRepository.UpdateAsync(site);
            _logger.LogInformation("网站 '{SiteId}' 更新成功。", id);
            return MapToSiteResponse(site);
        }

        /// <summary>
        /// 删除网站。
        /// </summary>
        /// <param name="id">要删除的网站ID。</param>
        /// <returns>如果删除成功则为true，否则为false。</returns>
        public async Task<bool> DeleteSiteAsync(string id)
        {
            _logger.LogInformation("尝试删除网站，ID: {SiteId}", id);
            var exists = await _siteRepository.ExistsAsync(id);
            if (!exists)
            {
                _logger.LogWarning("删除网站失败：未找到网站，ID: {SiteId}", id);
                return false;
            }
            await _siteRepository.DeleteAsync(id);
            _logger.LogInformation("网站 '{SiteId}' 删除成功。", id);
            return true;
        }

        /// <summary>
        /// 更新网站状态。
        /// </summary>
        /// <param name="id">要更新状态的网站ID。</param>
        /// <param name="request">包含新状态的请求数据。</param>
        /// <returns>更新后网站的响应DTO，如果网站不存在则为null。</returns>
        public async Task<SiteResponse?> UpdateSiteStatusAsync(string id, UpdateSiteStatusRequest request)
        {
            _logger.LogInformation("尝试更新网站状态，ID: {SiteId}, 新状态: {NewStatus}", id, request.Status);
            var site = await _siteRepository.GetByIdAsync(id);
            if (site == null)
            {
                _logger.LogWarning("更新网站状态失败：未找到网站，ID: {SiteId}", id);
                return null;
            }

            site.Status = request.Status;
            site.UpdatedAt = DateTime.UtcNow;

            await _siteRepository.UpdateAsync(site);
            _logger.LogInformation("网站 '{SiteId}' 状态更新成功，新状态: {NewStatus}", id, request.Status);
            return MapToSiteResponse(site);
        }


        // --- 私有辅助方法 ---

        /// <summary>
        /// 将 Site 实体映射到 SiteResponse DTO。
        /// </summary>
        private SiteResponse MapToSiteResponse(Site site)
        {
            return new SiteResponse
            {
                Id = site.Id,
                Name = site.Name,
                Domain = site.Domain,
                OwnerUserId = site.OwnerUserId,
                TeamMembers = site.TeamMembers?.Select(tm => new SiteTeamMemberDTO
                {
                    UserId = tm.UserId,
                    Role = tm.Role
                }).ToList(),
                Seo = site.Seo != null ? new SiteSeoDTO
                {
                    Description = site.Seo.Description,
                    Keywords = site.Seo.Keywords
                } : null,
                Analytics = site.Analytics != null ? new SiteAnalyticsDTO
                {
                    DailyVisitors = site.Analytics.DailyVisitors,
                    PopularGames = site.Analytics.PopularGames // 假设 PopularGames 已经是合适的字符串格式
                } : null,
                Settings = site.Settings != null ? new SiteSettingsDTO
                {
                    Theme = site.Settings.Theme,
                    Language = site.Settings.Language,
                    AdEnabled = site.Settings.AdEnabled
                } : null,
                Status = site.Status,
                CreatedAt = site.CreatedAt,
                UpdatedAt = site.UpdatedAt
            };
        }
    }
}