using iyixiGames.Domain.DTOs.Games;
using iyixiGames.Application.Services;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using System;
using iyixiGames.Infrastructure.Services;
using Microsoft.AspNetCore.Authorization; // 引入授权特性

namespace iyixiGames.Web.Controllers
{
    // 应用 [Authorize] 特性以保护整个控制器，只有登录用户才能访问。
    [Authorize]
    public class GamesController : Controller // 继承自 Controller，用于同时支持 MVC 和 API
    {
        private readonly IGameService _gameService;
        private readonly ILogger<GamesController> _logger;

        public GamesController(IGameService gameService, ILogger<GamesController> logger)
        {
            _gameService = gameService;
            _logger = logger;
        }

        // -----------------------------------------------------
        // 以下是 **MVC 视图相关** 的 Action 方法
        // -----------------------------------------------------

        /// <summary>
        /// MVC 视图：显示所有游戏的列表。
        /// GET: /Games 或 /Games/Index
        /// </summary>
        [HttpGet]
        [Route("Games")]
        [Route("Games/Index")]
        public async Task<IActionResult> Index()
        {
            _logger.LogInformation("MVC：用户请求访问游戏管理列表。");
            var games = await _gameService.GetAllGamesAsync();
            return View(games); // 返回视图并传递数据
        }

        /// <summary>
        /// MVC 视图：显示单个游戏的详细信息。
        /// GET: /Games/Details/{id}
        /// </summary>
        [HttpGet("Games/Details/{id}")]
        public async Task<IActionResult> Details(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                _logger.LogWarning("MVC：请求游戏详情但ID为空。");
                return NotFound();
            }

            var game = await _gameService.GetGameByIdAsync(id);
            if (game == null)
            {
                _logger.LogWarning("MVC：请求游戏详情，但未找到游戏 ID: {GameId}", id);
                return NotFound();
            }

            return View(game);
        }

        /// <summary>
        /// MVC 视图：显示创建新游戏的表单。
        /// GET: /Games/Create
        /// </summary>
        [HttpGet("Games/Create")]
        public IActionResult Create()
        {
            return View();
        }

        /// <summary>
        /// MVC 视图：处理创建新游戏的表单提交。
        /// POST: /Games/Create
        /// </summary>
        [HttpPost("Games/Create")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([FromForm] CreateGameRequest request)
        {
            _logger.LogInformation("MVC：接收到创建游戏的提交请求，名称: {GameName}", request.Name);
            if (ModelState.IsValid)
            {
                try
                {
                    var newGame = await _gameService.CreateGameAsync(request);
                    _logger.LogInformation("MVC：游戏 '{GameName}' (ID: {GameId}) 创建成功，重定向到详情页。", newGame.Name,
                        newGame.Id);
                    return RedirectToAction(nameof(Details), new { id = newGame.Id });
                }
                catch (InvalidOperationException ex)
                {
                    ModelState.AddModelError(string.Empty, ex.Message);
                    _logger.LogError(ex, "MVC：创建游戏时发生业务逻辑错误：{ErrorMessage}", ex.Message);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, "创建游戏时发生未知错误。");
                    _logger.LogError(ex, "MVC：创建游戏时发生服务器内部错误。");
                }
            }
            else
            {
                _logger.LogWarning("MVC：创建游戏失败：模型验证不通过。");
            }

            return View(request);
        }

        /// <summary>
        /// MVC 视图：显示编辑游戏信息的表单，预填充现有数据。
        /// GET: /Games/Edit/{id}
        /// </summary>
        [HttpGet("Games/Edit/{id}")]
        public async Task<IActionResult> Edit(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                _logger.LogWarning("MVC: Request to edit game with empty ID.");
                return NotFound();
            }

            var game = await _gameService.GetGameByIdAsync(id);
            if (game == null)
            {
                _logger.LogWarning("MVC: Request to edit game, but game not found ID: {GameId}", id);
                return NotFound();
            }

            var updateRequest = new UpdateGameRequest
            {
                Name = game.Name,
                Path = game.Path,
                Description = game.Description, // <--- New: Populate description
                Category = string.Join(",", game.Category),
                Popularity = game.Popularity,
                AvgRating = game.AvgRating,
                ReleaseDate = game.ReleaseDate
            };

            ViewBag.GameId = id;
            ViewBag.GameName = game.Name;
            return View(updateRequest);
        }

        /// <summary>
        /// MVC 视图：处理编辑游戏信息的表单提交。
        /// POST: /Games/Edit/{id}
        /// </summary>
        [HttpPost("Games/Edit/{id}")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(string id, [FromForm] UpdateGameRequest request)
        {
            _logger.LogInformation("MVC：接收到更新游戏 ID: {GameId} 的提交请求。", id);
            if (string.IsNullOrEmpty(id))
            {
                _logger.LogWarning("MVC：更新游戏时ID为空。");
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    var updatedGame = await _gameService.UpdateGameAsync(id, request);
                    if (updatedGame == null)
                    {
                        _logger.LogWarning("MVC：更新游戏失败：未找到游戏 ID: {GameId}。", id);
                        return NotFound();
                    }

                    _logger.LogInformation("MVC：游戏 '{GameId}' 更新成功，重定向到详情页。", id);
                    return RedirectToAction(nameof(Details), new { id = id });
                }
                catch (InvalidOperationException ex)
                {
                    ModelState.AddModelError(string.Empty, ex.Message);
                    _logger.LogError(ex, "MVC：更新游戏时发生业务逻辑错误：{ErrorMessage}", ex.Message);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, "更新游戏时发生未知错误。");
                    _logger.LogError(ex, "MVC：更新游戏时发生服务器内部错误。");
                }
            }
            else
            {
                _logger.LogWarning("MVC：更新游戏失败：模型验证不通过。");
            }

            ViewBag.GameId = id;
            ViewBag.GameName = request.Name ?? "未知游戏";
            return View(request);
        }

        /// <summary>
        /// MVC 视图：显示删除确认页。
        /// GET: /Games/Delete/{id}
        /// </summary>
        [HttpGet("Games/Delete/{id}")]
        public async Task<IActionResult> Delete(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                _logger.LogWarning("MVC：请求删除游戏但ID为空。");
                return NotFound();
            }

            var game = await _gameService.GetGameByIdAsync(id);
            if (game == null)
            {
                _logger.LogWarning("MVC：请求删除游戏，但未找到游戏 ID: {GameId}", id);
                return NotFound();
            }

            return View(game);
        }

        /// <summary>
        /// MVC 视图：处理删除游戏的 POST 请求。
        /// POST: /Games/Delete/{id}
        /// </summary>
        [HttpPost("Games/Delete/{id}")]
        [ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(string id)
        {
            _logger.LogInformation("MVC：接收到确认删除游戏 ID: {GameId} 的请求。", id);
            if (string.IsNullOrEmpty(id))
            {
                _logger.LogWarning("MVC：确认删除游戏时ID为空。");
                return NotFound();
            }

            var deleted = await _gameService.DeleteGameAsync(id);
            if (!deleted)
            {
                _logger.LogWarning("MVC：删除游戏失败：未找到游戏 ID: {GameId}。", id);
                return NotFound();
            }

            _logger.LogInformation("MVC：游戏 '{GameId}' 成功删除，重定向到列表页。", id);
            return RedirectToAction(nameof(Index));
        }

        // -----------------------------------------------------
        // 以下是 **Web API 相关** 的 Action 方法
        // 它们通常返回 ActionResult<T> 或 ActionResult
        // 并带有 [Route("api/games")] 作为基路由
        // -----------------------------------------------------

        /// <summary>
        /// API：获取所有游戏列表。
        /// GET: /api/games
        /// </summary>
        [HttpGet("api/games")] // 明确指定 API 路由
        [ProducesResponseType(typeof(IEnumerable<GameResponse>), 200)]
        public async Task<ActionResult<IEnumerable<GameResponse>>> GetApiAllGames()
        {
            _logger.LogInformation("API：接收到获取所有游戏的请求。");
            var games = await _gameService.GetAllGamesAsync();
            return Ok(games);
        }

        /// <summary>
        /// API：根据ID获取单个游戏详情。
        /// GET: /api/games/{id}
        /// </summary>
        [HttpGet("api/games/{id}")] // 明确指定 API 路由
        [ProducesResponseType(typeof(GameResponse), 200)]
        [ProducesResponseType(404)]
        public async Task<ActionResult<GameResponse>> GetApiGameById(string id)
        {
            _logger.LogInformation("API：接收到获取游戏 ID: {GameId} 的请求。", id);
            var game = await _gameService.GetGameByIdAsync(id);
            if (game == null)
            {
                _logger.LogWarning("API：获取游戏失败：未找到游戏 ID: {GameId}。", id);
                return NotFound();
            }

            return Ok(game);
        }

        /// <summary>
        /// API：创建新游戏。
        /// POST: /api/games
        /// </summary>
        [HttpPost("api/games")] // 明确指定 API 路由
        [ProducesResponseType(typeof(GameResponse), 201)]
        [ProducesResponseType(400)]
        [ProducesResponseType(409)] // Conflict for name exists
        public async Task<ActionResult<GameResponse>> CreateApiGame([FromBody] CreateGameRequest request)
        {
            _logger.LogInformation("API：接收到创建新游戏的请求，名称: {GameName}", request.Name);
            if (!ModelState.IsValid)
            {
                _logger.LogWarning("API：创建游戏失败：模型验证不通过。");
                return BadRequest(ModelState);
            }

            try
            {
                var newGame = await _gameService.CreateGameAsync(request);
                return CreatedAtAction(nameof(GetApiGameById), new { id = newGame.Id }, newGame);
            }
            catch (InvalidOperationException ex)
            {
                _logger.LogError(ex, "API：创建游戏失败：{ErrorMessage}", ex.Message);
                return Conflict(new { message = ex.Message }); // 返回409冲突
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "API：创建游戏时发生服务器内部错误。");
                return StatusCode(500, "内部服务器错误。");
            }
        }

        /// <summary>
        /// API：更新游戏信息。
        /// PUT: /api/games/{id}
        /// </summary>
        [HttpPut("api/games/{id}")] // 明确指定 API 路由
        [ProducesResponseType(typeof(GameResponse), 200)]
        [ProducesResponseType(400)]
        [ProducesResponseType(404)]
        [ProducesResponseType(409)] // Conflict for name exists
        public async Task<ActionResult<GameResponse>> UpdateApiGame(string id, [FromBody] UpdateGameRequest request)
        {
            _logger.LogInformation("API：接收到更新游戏 ID: {GameId} 的请求。", id);
            if (!ModelState.IsValid)
            {
                _logger.LogWarning("API：更新游戏失败：模型验证不通过。");
                return BadRequest(ModelState);
            }

            try
            {
                var updatedGame = await _gameService.UpdateGameAsync(id, request);
                if (updatedGame == null)
                {
                    _logger.LogWarning("API：更新游戏失败：未找到游戏 ID: {GameId}。", id);
                    return NotFound();
                }

                return Ok(updatedGame);
            }
            catch (InvalidOperationException ex)
            {
                _logger.LogError(ex, "API：更新游戏失败：{ErrorMessage}", ex.Message);
                return Conflict(new { message = ex.Message }); // 返回409冲突
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "API：更新游戏时发生服务器内部错误。");
                return StatusCode(500, "内部服务器错误。");
            }
        }

        /// <summary>
        /// API：删除游戏。
        /// DELETE: /api/games/{id}
        /// </summary>
        [HttpDelete("api/games/{id}")] // 明确指定 API 路由
        [ProducesResponseType(204)] // No Content
        [ProducesResponseType(404)]
        public async Task<ActionResult> DeleteApiGame(string id)
        {
            _logger.LogInformation("API：接收到删除游戏 ID: {GameId} 的请求。", id);
            var deleted = await _gameService.DeleteGameAsync(id);
            if (!deleted)
            {
                _logger.LogWarning("API：删除游戏失败：未找到游戏 ID: {GameId}。", id);
                return NotFound();
            }

            return NoContent(); // 删除成功，返回204 No Content
        }

        // -----------------------------------------------------
        // 新增：MVC 视图批量创建 Action
        // -----------------------------------------------------

        /// <summary>
        /// MVC 视图：处理批量创建游戏的请求。
        /// POST: /Games/BatchCreate
        /// </summary>
        [HttpPost("Games/BatchCreate")] // 明确指定 MVC 路由
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> BatchCreate([FromForm] BatchCreateGamesRequest request)
        {
            _logger.LogInformation("MVC：接收到批量创建游戏的提交请求。");
            if (ModelState.IsValid)
            {
                try
                {
                    var createdGames = await _gameService.BatchCreateGamesAsync(request);
                    _logger.LogInformation("MVC：成功批量创建 {Count} 个游戏。", createdGames.Count);
                    TempData["SuccessMessage"] = $"成功批量创建 {createdGames.Count} 个游戏。";
                    return RedirectToAction(nameof(Index)); // 批量创建后重定向到列表页
                }
                catch (InvalidOperationException ex)
                {
                    ModelState.AddModelError(string.Empty, ex.Message);
                    _logger.LogError(ex, "MVC：批量创建游戏时发生业务逻辑错误：{ErrorMessage}", ex.Message);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, "批量创建游戏时发生未知错误。");
                    _logger.LogError(ex, "MVC：批量创建游戏时发生服务器内部错误。");
                }
            }
            else
            {
                _logger.LogWarning("MVC：批量创建游戏失败：模型验证不通过。");
            }

            // 如果模型无效或发生错误，重新显示 Index 页面（可能需要传递现有游戏列表）
            // 这里为了简化，直接重定向回 Index，但更好的做法是重新加载并显示错误。
            // 考虑使用 ViewBag 或 TempData 传递错误信息。
            TempData["ErrorMessage"] = "批量创建失败，请检查输入或查看日志。";
            return RedirectToAction(nameof(Index));
        }

        // -----------------------------------------------------
        // New: AJAX Action for Description Generation
        // -----------------------------------------------------

        /// <summary>
        /// API endpoint to generate a game description using DeepSeek AI.
        /// POST: /Games/GenerateDescription
        /// </summary>
        /// <param name="gameName">The name of the game for which to generate a description.</param>
        /// <returns>JSON result containing the generated description or an error message.</returns>
        [HttpPost("Games/GenerateDescription")]
        public async Task<IActionResult> GenerateDescription([FromForm] string gameName)
        {
            if (string.IsNullOrWhiteSpace(gameName))
            {
                return BadRequest("游戏名称不能为空。");
            }

            try
            {
                var description = await _gameService.GenerateGameDescriptionAsync(gameName);
                if (description != null)
                {
                    return Json(new { success = true, description = description });
                }

                return Json(new { success = false, message = "未能生成游戏简介，请稍后再试或手动输入。" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成游戏简介时发生错误: {GameName}", gameName);
                return StatusCode(500, new { success = false, message = "服务器错误，生成简介失败。" });
            }
        }

        // ... existing BatchCreate action ...
        // ... existing API actions (GetApiAllGames, GetApiGameById, CreateApiGame, UpdateApiGame, DeleteApiGame) ...
        [HttpPost("Games/GenerateGameInfoFromPath")]
        public async Task<IActionResult> GenerateGameInfoFromPath([FromForm] string gamePath)
        {
            if (string.IsNullOrWhiteSpace(gamePath))
            {
                return BadRequest("游戏路径不能为空。");
            }

            try
            {
                var game = await _gameService.GenerateGameInfoFromPathAsync(gamePath);
                if (game != null)
                {
                    return Json(new { success = true, description = game });
                    // return Ok(game);
                }
                return Json(new { success = false, message = "游戏信息生成失败。" });
            }
            catch (Exception e)
            {
                _logger.LogError(e, "生成游戏信息时出错。");
                return StatusCode(500, "服务器内部错误。");
            }
        }
    }
}