using AcdiuTools.Models;
using AcdiuTools.Services;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Security.Claims;

namespace AcdiuTools.Controllers
{
    public class HomeController(IThemeService themeService) : BaseController(themeService)
    {
        private readonly IThemeService _themeService = themeService;

        [Route("")]
        public IActionResult Index()
        {
            return View();
        }

        [Route("privacy")]
        public IActionResult Privacy()
        {
            return View();
        }

        [Route("err")]
        [Route("error")]
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        /// <summary>
        /// API 端点：用于前端 AJAX 调用以切换主题
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> SetTheme([FromBody] ThemeRequest model)
        {
            // 获取用户 ID
            string? claimUserId = User.FindFirst(ClaimTypes.NameIdentifier)?.Value
                               ?? User.FindFirst("sub")?.Value;

            string userId;

            if (!string.IsNullOrEmpty(claimUserId))
            {
                // 已登录用户
                userId = claimUserId;
            }
            else
            {
                // 匿名用户：尝试使用 Session ID
                // 注意：访问 HttpContext.Session 会触发 Session 创建/加载
                try
                {
                    userId = HttpContext.Session.Id;
                }
                catch (InvalidOperationException)
                {
                    // 如果 Session 未配置（防御性编程），回退到匿名标识
                    userId = "anonymous_" + HttpContext.Connection.RemoteIpAddress?.ToString()?.Replace(".", "_") ?? "unknown";
                }
            }

            await _themeService.SaveUserThemeAsync(userId, model.Theme);

            return Json(new { success = true, theme = model.Theme });
        }
    }

    /// <summary>
    /// 主题请求模型
    /// </summary>
    public class ThemeRequest
    {
        /// <summary>
        /// 主题名称
        /// 修复 CS8618: 使用 required 修饰符，确保反序列化时必须存在该字段
        /// </summary>
        [Required]
        public required string Theme { get; set; }
    }
}