using System.Security.Claims;
using HoneyBox.Admin.Filters;
using HoneyBox.Admin.Models.AdminUser;
using HoneyBox.Admin.Models.Common;
using HoneyBox.Admin.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace HoneyBox.Admin.Controllers;

/// <summary>
/// 管理员管理控制器
/// </summary>
[ApiController]
[Route("api/admin/users")]
[Authorize]
public class AdminUserController : ControllerBase
{
    private readonly IAdminUserService _adminUserService;
    private readonly ILogger<AdminUserController> _logger;

    public AdminUserController(IAdminUserService adminUserService, ILogger<AdminUserController> logger)
    {
        _adminUserService = adminUserService;
        _logger = logger;
    }

    /// <summary>
    /// 获取管理员分页列表
    /// </summary>
    /// <param name="request">查询请求</param>
    /// <returns>分页结果</returns>
    [HttpGet]
    public async Task<ApiResponse<PagedResult<AdminUserDto>>> GetList([FromQuery] AdminUserQueryRequest request)
    {
        var result = await _adminUserService.GetListAsync(request);
        return ApiResponse<PagedResult<AdminUserDto>>.Success(result);
    }

    /// <summary>
    /// 获取管理员详情
    /// </summary>
    /// <param name="id">管理员ID</param>
    /// <returns>管理员详情</returns>
    [HttpGet("{id:long}")]
    public async Task<ApiResponse<AdminUserDto>> GetById(long id)
    {
        var result = await _adminUserService.GetByIdAsync(id);
        return ApiResponse<AdminUserDto>.Success(result);
    }

    /// <summary>
    /// 创建管理员
    /// </summary>
    /// <param name="request">创建请求</param>
    /// <returns>新管理员ID</returns>
    [HttpPost]
    [OperationLog("管理员管理", "创建管理员")]
    public async Task<ApiResponse<long>> Create([FromBody] CreateAdminUserRequest request)
    {
        var createdBy = GetCurrentUserId();
        var id = await _adminUserService.CreateAsync(request, createdBy);
        return ApiResponse<long>.Success(id, "创建成功");
    }

    /// <summary>
    /// 更新管理员
    /// </summary>
    /// <param name="id">管理员ID</param>
    /// <param name="request">更新请求</param>
    [HttpPut("{id:long}")]
    [OperationLog("管理员管理", "更新管理员")]
    public async Task<ApiResponse> Update(long id, [FromBody] UpdateAdminUserRequest request)
    {
        await _adminUserService.UpdateAsync(id, request);
        return ApiResponse.Success("更新成功");
    }

    /// <summary>
    /// 删除管理员
    /// </summary>
    /// <param name="id">管理员ID</param>
    [HttpDelete("{id:long}")]
    [OperationLog("管理员管理", "删除管理员")]
    public async Task<ApiResponse> Delete(long id)
    {
        await _adminUserService.DeleteAsync(id);
        return ApiResponse.Success("删除成功");
    }

    /// <summary>
    /// 获取管理员已分配的角色ID列表
    /// </summary>
    /// <param name="id">管理员ID</param>
    /// <returns>角色ID列表</returns>
    [HttpGet("{id:long}/roles")]
    public async Task<ApiResponse<List<long>>> GetRoles(long id)
    {
        var result = await _adminUserService.GetRoleIdsAsync(id);
        return ApiResponse<List<long>>.Success(result);
    }

    /// <summary>
    /// 分配角色给管理员
    /// </summary>
    /// <param name="id">管理员ID</param>
    /// <param name="request">分配请求</param>
    [HttpPut("{id:long}/roles")]
    [OperationLog("管理员管理", "分配角色")]
    public async Task<ApiResponse> AssignRoles(long id, [FromBody] AssignRolesRequest request)
    {
        await _adminUserService.AssignRolesAsync(id, request.RoleIds);
        return ApiResponse.Success("分配成功");
    }

    /// <summary>
    /// 获取管理员已分配的专属菜单ID列表
    /// </summary>
    /// <param name="id">管理员ID</param>
    /// <returns>菜单ID列表</returns>
    [HttpGet("{id:long}/menus")]
    public async Task<ApiResponse<List<long>>> GetMenus(long id)
    {
        var result = await _adminUserService.GetMenuIdsAsync(id);
        return ApiResponse<List<long>>.Success(result);
    }

    /// <summary>
    /// 分配用户专属菜单
    /// </summary>
    /// <param name="id">管理员ID</param>
    /// <param name="request">分配请求</param>
    [HttpPut("{id:long}/menus")]
    [OperationLog("管理员管理", "分配专属菜单")]
    public async Task<ApiResponse> AssignMenus(long id, [FromBody] AssignUserMenusRequest request)
    {
        await _adminUserService.AssignMenusAsync(id, request.MenuIds);
        return ApiResponse.Success("分配成功");
    }

    /// <summary>
    /// 分配部门
    /// </summary>
    /// <param name="id">管理员ID</param>
    /// <param name="request">分配请求</param>
    [HttpPut("{id:long}/department")]
    [OperationLog("管理员管理", "分配部门")]
    public async Task<ApiResponse> AssignDepartment(long id, [FromBody] AssignDepartmentRequest request)
    {
        await _adminUserService.AssignDepartmentAsync(id, request.DepartmentId);
        return ApiResponse.Success("分配成功");
    }

    /// <summary>
    /// 设置管理员状态
    /// </summary>
    /// <param name="id">管理员ID</param>
    /// <param name="request">状态请求</param>
    [HttpPut("{id:long}/status")]
    [OperationLog("管理员管理", "设置状态")]
    public async Task<ApiResponse> SetStatus(long id, [FromBody] SetStatusRequest request)
    {
        var ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown";
        await _adminUserService.SetStatusAsync(id, request.Status == 1, ipAddress);
        return ApiResponse.Success("设置成功");
    }

    /// <summary>
    /// 重置密码
    /// </summary>
    /// <param name="id">管理员ID</param>
    /// <param name="request">重置密码请求</param>
    [HttpPut("{id:long}/reset-password")]
    [OperationLog("管理员管理", "重置密码")]
    public async Task<ApiResponse> ResetPassword(long id, [FromBody] ResetPasswordRequest request)
    {
        await _adminUserService.ResetPasswordAsync(id, request.NewPassword);
        return ApiResponse.Success("密码重置成功");
    }

    /// <summary>
    /// 获取当前用户ID
    /// </summary>
    private long GetCurrentUserId()
    {
        var userIdClaim = User.FindFirst(ClaimTypes.NameIdentifier);
        if (userIdClaim == null || !long.TryParse(userIdClaim.Value, out var userId))
        {
            throw new AdminException(AdminErrorCodes.TokenInvalid, "无效的用户身份");
        }
        return userId;
    }
}
