using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using QYZH.InteractiveMagazine.IService;

using QYZH.InteractiveMagazine.Models.Common;
using QYZH.InteractiveMagazine.Models.Dto;
using QYZH.InteractiveMagazine.Models.Enum;

namespace QYZH.InteractiveMagazine.WebApi.Controllers;


[Route("api/[controller]")]
[ApiController]
public class AdminController : BaseController
{
    private readonly IAdminAuthService _adminAuthService;
    private readonly IAdminUserService _adminUserService;
    private readonly ILogger<AdminController> _logger;

    public AdminController(IAdminAuthService adminAuthService, IAdminUserService adminUserService, ILogger<AdminController> logger)
    {
        _adminAuthService = adminAuthService;
        _adminUserService = adminUserService;
        _logger = logger;
    }

    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="input">登录输入</param>
    /// <returns>登录结果</returns>
    [AllowAnonymous]
    [HttpPost("login")]
    public async Task<BaseResponse<AdminLoginOutput>> LoginAsync([FromBody] AdminLoginInput input)
    {
        var result = await _adminAuthService.LoginAsync(input);
        return Success(result);
    }

    /// <summary>
    /// 登出
    /// </summary>
    /// <returns>登出结果</returns>
    [HttpPost("logout")]
    public async Task<BaseResponse<object>> LogoutAsync()
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return Fail("未获取到用户信息", 401);
        }

        await _adminAuthService.LogoutAsync(userId.Value);
        return Success(new object(), "登出成功");
    }

    /// <summary>
    /// 获取管理员信息
    /// </summary>
    /// <returns>管理员信息</returns>
    [HttpGet("info")]
    public async Task<BaseResponse<AdminUserInfoOutput>> GetAdminInfoAsync()
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return BaseResponse<AdminUserInfoOutput>.Fail(ResultCode.DENY, "未获取到用户信息");
        }

        var result = await _adminAuthService.GetAdminInfoAsync(userId.Value);
        return Success(result);
    }

    /// <summary>
    /// 修改密码
    /// </summary>
    /// <param name="input">修改密码输入</param>
    /// <returns>修改密码结果</returns>
    [HttpPost("changePassword")]
    public async Task<BaseResponse<object>> ChangePasswordAsync([FromBody] ChangePasswordInput input)
    {
        var userId = GetCurrentUserId();
        if (userId == null)
        {
            return Fail("未获取到用户信息", 401);
        }

        await _adminAuthService.ChangePasswordAsync(userId.Value, input.OldPassword, input.NewPassword);
        return Success(new object(), "密码修改成功");
    }

    /// <summary>
    /// 创建管理员
    /// </summary>
    /// <param name="input">管理员输入</param>
    /// <returns>创建的管理员信息</returns>
    [HttpPost("users")]
    public async Task<BaseResponse<AdminUserOutput>> CreateUserAsync([FromBody] AdminUserInput input)
    {
        try
        {
            var result = await _adminUserService.CreateAsync(input);
            return Success(result, "创建管理员成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "创建管理员业务异常: {Message}", ex.Message);
            return BaseResponse<AdminUserOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建管理员系统异常，参数：{Input}", input);
            return BaseResponse<AdminUserOutput>.Fail("创建管理员失败，请稍后重试");
        }
    }

    /// <summary>
    /// 更新管理员
    /// </summary>
    /// <param name="id">管理员ID</param>
    /// <param name="input">管理员输入</param>
    /// <returns>更新后的管理员信息</returns>
    [HttpPut("users/{id}")]
    public async Task<BaseResponse<AdminUserOutput>> UpdateUserAsync(long id, [FromBody] AdminUserInput input)
    {
        try
        {
            var result = await _adminUserService.UpdateAsync(id, input);
            return Success(result, "更新管理员成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "更新管理员业务异常: {Message}", ex.Message);
            return BaseResponse<AdminUserOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新管理员系统异常，ID：{Id}，参数：{Input}", id, input);
            return BaseResponse<AdminUserOutput>.Fail("更新管理员失败，请稍后重试");
        }
    }

    /// <summary>
    /// 删除管理员
    /// </summary>
    /// <param name="id">管理员ID</param>
    /// <returns>操作结果</returns>
    [HttpDelete("users/{id}")]
    public async Task<BaseResponse<object>> DeleteUserAsync(long id)
    {
        try
        {
            await _adminUserService.DeleteAsync(id);
            return Success(new object(), "删除管理员成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "删除管理员业务异常: {Message}", ex.Message);
            return BaseResponse<object>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除管理员系统异常，ID：{Id}", id);
            return BaseResponse<object>.Fail("删除管理员失败，请稍后重试");
        }
    }

    /// <summary>
    /// 根据ID获取管理员
    /// </summary>
    /// <param name="id">管理员ID</param>
    /// <returns>管理员信息</returns>
    [HttpGet("users/{id}")]
    public async Task<BaseResponse<AdminUserOutput>> GetUserByIdAsync(long id)
    {
        try
        {
            var result = await _adminUserService.GetByIdAsync(id);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "获取管理员业务异常: {Message}", ex.Message);
            return BaseResponse<AdminUserOutput>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取管理员系统异常，ID：{Id}", id);
            return BaseResponse<AdminUserOutput>.Fail("获取管理员信息失败，请稍后重试");
        }
    }

    /// <summary>
    /// 分页查询管理员列表
    /// </summary>
    /// <param name="input">查询条件</param>
    /// <returns>分页结果</returns>
    [HttpPost("users/list")]
    public async Task<BaseResponse<PageListModel<AdminUserOutput>>> GetUsersListAsync([FromBody] AdminUserQueryInput input)
    {
        try
        {
            var result = await _adminUserService.GetListAsync(input);
            return Success(result);
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "查询管理员列表业务异常: {Message}", ex.Message);
            return BaseResponse<PageListModel<AdminUserOutput>>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "查询管理员列表系统异常，参数：{Input}", input);
            return BaseResponse<PageListModel<AdminUserOutput>>.Fail("查询管理员列表失败，请稍后重试");
        }
    }

    /// <summary>
    /// 切换管理员状态（激活/冻结）
    /// </summary>
    /// <param name="id">管理员ID</param>
    /// <returns>操作结果</returns>
    [HttpPut("users/{id}/status")]
    public async Task<BaseResponse<object>> ToggleUserStatusAsync(long id)
    {
        try
        {
            await _adminUserService.ToggleStatusAsync(id);
            return Success(new object(), "切换管理员状态成功");
        }
        catch (BusinessException ex)
        {
            _logger.LogWarning(ex, "切换管理员状态业务异常: {Message}", ex.Message);
            return BaseResponse<object>.Fail(ex.Message);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "切换管理员状态系统异常，ID：{Id}", id);
            return BaseResponse<object>.Fail("切换状态失败，请稍后重试");
        }
    }
}

public class ChangePasswordInput
{
    public string OldPassword { get; set; } = string.Empty;

    public string NewPassword { get; set; } = string.Empty;
}
