using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

/// <summary>
/// User directory, management, and password operations.
/// </summary>
[ApiController]
[Route("api/v1/users")]
[Produces("application/json")]
[Authorize]
public class UsersController : ControllerBase
{
    private readonly IUserDirectoryService _users;

    public UsersController(IUserDirectoryService users) => _users = users;

    /// <summary>
    /// Lists active users, optionally filtered by role.
    /// </summary>
    [HttpGet]
    [Authorize(Roles = "INTAKE_CLERK,ADMINISTRATOR")]
    [ProducesResponseType(typeof(ApiResponse<IReadOnlyList<UserSummaryResponse>>), StatusCodes.Status200OK)]
    public async Task<IActionResult> List([FromQuery] string? role)
    {
        UserRole? parsedRole = null;
        if (!string.IsNullOrWhiteSpace(role))
            parsedRole = UserRoleExtensions.FromDbString(role);

        var results = await _users.ListByRoleAsync(parsedRole);
        return Ok(ApiResponse<IReadOnlyList<UserSummaryResponse>>.Ok(results));
    }

    /// <summary>
    /// Creates a new user. Admin only.
    /// </summary>
    [HttpPost]
    [Authorize(Roles = "ADMINISTRATOR")]
    [ProducesResponseType(typeof(ApiResponse<UserSummaryResponse>), StatusCodes.Status201Created)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status409Conflict)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status422UnprocessableEntity)]
    public async Task<IActionResult> Create([FromBody] CreateUserRequest request)
    {
        var result = await _users.CreateAsync(request);
        return StatusCode(201, ApiResponse<UserSummaryResponse>.Created(result));
    }

    /// <summary>
    /// Updates user details (fullName, role, isActive). Admin only.
    /// </summary>
    [HttpPatch("{id:guid}")]
    [Authorize(Roles = "ADMINISTRATOR")]
    [ProducesResponseType(typeof(ApiResponse<UserSummaryResponse>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status422UnprocessableEntity)]
    public async Task<IActionResult> Update(Guid id, [FromBody] UpdateUserRequest request)
    {
        var result = await _users.UpdateAsync(id, request);
        return Ok(ApiResponse<UserSummaryResponse>.Ok(result));
    }

    /// <summary>
    /// Admin password reset for any user.
    /// </summary>
    [HttpPost("{id:guid}/reset-password")]
    [Authorize(Roles = "ADMINISTRATOR")]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status422UnprocessableEntity)]
    public async Task<IActionResult> ResetPassword(Guid id, [FromBody] ResetPasswordRequest request)
    {
        await _users.ResetPasswordAsync(id, request.NewPassword);
        return NoContent();
    }

    /// <summary>
    /// Self-service password change. Requires current password.
    /// </summary>
    [HttpPost("me/change-password")]
    [Authorize]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status422UnprocessableEntity)]
    public async Task<IActionResult> ChangePassword([FromBody] ChangePasswordRequest request)
    {
        var userId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
        await _users.ChangePasswordAsync(userId, request.CurrentPassword, request.NewPassword);
        return NoContent();
    }
}
