using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

/// <summary>
/// Clinical user account management for hospital IT administrators.
/// </summary>
[ApiController]
[Route("api/v1/users")]
[Produces("application/json")]
[Authorize]
public class UsersController : ControllerBase
{
    private readonly IUserService _users;

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

    /// <summary>Lists all clinical user accounts.</summary>
    [HttpGet]
    [AuthorizePermission(ClinicalPermissions.UsersAdmin)]
    [ProducesResponseType(typeof(ApiResponse<List<ClinicalUserResponse>>), StatusCodes.Status200OK)]
    public async Task<IActionResult> List()
    {
        var users = await _users.ListAsync();
        return Ok(ApiResponse<List<ClinicalUserResponse>>.Ok(users));
    }

    /// <summary>Creates a new clinical user account.</summary>
    [HttpPost]
    [AuthorizePermission(ClinicalPermissions.UsersAdmin)]
    [ProducesResponseType(typeof(ApiResponse<ClinicalUserResponse>), StatusCodes.Status201Created)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status409Conflict)]
    public async Task<IActionResult> Create([FromBody] CreateUserRequest req)
    {
        var user = await _users.CreateAsync(req);
        return StatusCode(201, ApiResponse<ClinicalUserResponse>.Created(user));
    }

    /// <summary>Updates role, display name, or active status for a user.</summary>
    [HttpPatch("{id:guid}")]
    [AuthorizePermission(ClinicalPermissions.UsersAdmin)]
    [ProducesResponseType(typeof(ApiResponse<ClinicalUserResponse>), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
    public async Task<IActionResult> Update(Guid id, [FromBody] UpdateUserRequest req)
    {
        var user = await _users.UpdateAsync(id, req);
        return Ok(ApiResponse<ClinicalUserResponse>.Ok(user));
    }
}
