using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using ROLAC.API.Authorization;
using ROLAC.API.DTOs.Users;
using ROLAC.API.Services;

namespace ROLAC.API.Controllers;

[ApiController]
[Route("api/users")]
[Authorize]
public class UsersController : ControllerBase
{
    private readonly IUserManagementService _users;
    public UsersController(IUserManagementService users) => _users = users;

    /// <summary>GET /api/users?page=1&pageSize=20&search=Chris</summary>
    [HttpGet]
    [HasPermission(Modules.Users, PermissionActions.Read)]
    public async Task<IActionResult> GetPaged(
        [FromQuery] int     page     = 1,
        [FromQuery] int     pageSize = 20,
        [FromQuery] string? search   = null)
        => Ok(await _users.GetPagedAsync(page, pageSize, search));

    /// <summary>GET /api/users/{id}</summary>
    [HttpGet("{id}")]
    [HasPermission(Modules.Users, PermissionActions.Read)]
    public async Task<IActionResult> GetById(string id)
    {
        var dto = await _users.GetByIdAsync(id);
        return dto is null ? NotFound() : Ok(dto);
    }

    /// <summary>
    /// POST /api/users — creates account for a Member, returns { userId, tempPassword }.
    /// TempPassword is returned ONCE — show it to the admin and never log it.
    /// </summary>
    [HttpPost]
    [HasPermission(Modules.Users, PermissionActions.Write)]
    public async Task<IActionResult> Create([FromBody] CreateUserRequest request)
    {
        try
        {
            var result = await _users.CreateAsync(request);
            return Ok(result);
        }
        catch (InvalidOperationException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    /// <summary>PUT /api/users/{id} — update email, roles, IsActive</summary>
    [HttpPut("{id}")]
    [HasPermission(Modules.Users, PermissionActions.Write)]
    public async Task<IActionResult> Update(string id, [FromBody] UpdateUserRequest request)
    {
        try   { await _users.UpdateAsync(id, request); return NoContent(); }
        catch (KeyNotFoundException)          { return NotFound(); }
        catch (InvalidOperationException ex)  { return BadRequest(new { message = ex.Message }); }
    }

    /// <summary>DELETE /api/users/{id} — deactivates account (IsActive=false), does not delete</summary>
    [HttpDelete("{id}")]
    [HasPermission(Modules.Users, PermissionActions.Delete)]
    public async Task<IActionResult> Deactivate(string id)
    {
        try   { await _users.DeactivateAsync(id); return NoContent(); }
        catch (KeyNotFoundException) { return NotFound(); }
    }

    /// <summary>POST /api/users/{id}/reset-password — returns new temp password</summary>
    [HttpPost("{id}/reset-password")]
    [HasPermission(Modules.Users, PermissionActions.Write)]
    public async Task<IActionResult> ResetPassword(string id)
    {
        try
        {
            var pwd = await _users.ResetPasswordAsync(id);
            return Ok(new { tempPassword = pwd });
        }
        catch (KeyNotFoundException) { return NotFound(); }
    }
}
