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

namespace ROLAC.API.Controllers;

[ApiController]
[Route("api/members")]
[Authorize]
public class MembersController : ControllerBase
{
    private readonly IMemberService _members;
    public MembersController(IMemberService members) => _members = members;

    /// <summary>GET /api/members?page=1&pageSize=20&search=Chen&status=Member&hasUser=false</summary>
    [HttpGet]
    [HasPermission(Modules.Members, PermissionActions.Read)]
    public async Task<IActionResult> GetPaged(
        [FromQuery] int     page     = 1,
        [FromQuery] int     pageSize = 20,
        [FromQuery] string? search   = null,
        [FromQuery] string? status   = null,
        [FromQuery] bool?   hasUser  = null)
        => Ok(await _members.GetPagedAsync(page, pageSize, search, status, hasUser));

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

    /// <summary>POST /api/members</summary>
    [HttpPost]
    [HasPermission(Modules.Members, PermissionActions.Write)]
    public async Task<IActionResult> Create([FromBody] CreateMemberRequest request)
    {
        var id = await _members.CreateAsync(request);
        return CreatedAtAction(nameof(GetById), new { id }, new { id });
    }

    /// <summary>PUT /api/members/{id}</summary>
    [HttpPut("{id:int}")]
    [HasPermission(Modules.Members, PermissionActions.Write)]
    public async Task<IActionResult> Update(int id, [FromBody] UpdateMemberRequest request)
    {
        try   { await _members.UpdateAsync(id, request); return NoContent(); }
        catch (KeyNotFoundException) { return NotFound(); }
    }

    /// <summary>DELETE /api/members/{id} — soft delete</summary>
    [HttpDelete("{id:int}")]
    [HasPermission(Modules.Members, PermissionActions.Delete)]
    public async Task<IActionResult> Delete(int id)
    {
        try   { await _members.DeleteAsync(id); return NoContent(); }
        catch (KeyNotFoundException) { return NotFound(); }
    }
}
