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

namespace ROLAC.API.Controllers;

/// <summary>
/// Admin endpoints for generating and e-mailing first-login invitation links.
/// The public consume/validate endpoints live on <see cref="AuthController"/> so they can set the
/// refresh-token cookie and stay anonymous.
/// </summary>
[ApiController]
[Route("api/invitations")]
[Authorize]
public class InvitationsController : ControllerBase
{
    private readonly IInvitationService _invitations;
    public InvitationsController(IInvitationService invitations) => _invitations = invitations;

    /// <summary>POST /api/invitations — generate a link for a member; returns { token, expiresAt }.</summary>
    [HttpPost]
    [HasPermission(Modules.Users, PermissionActions.Write)]
    public async Task<IActionResult> Create([FromBody] CreateInvitationRequest request)
    {
        try   { return Ok(await _invitations.CreateAsync(request)); }
        catch (InvalidOperationException ex) { return BadRequest(new { message = ex.Message }); }
    }

    /// <summary>POST /api/invitations/send — e-mail an already-generated link to the member.</summary>
    [HttpPost("send")]
    [HasPermission(Modules.Users, PermissionActions.Write)]
    public async Task<IActionResult> Send([FromBody] SendInvitationRequest request)
    {
        try   { await _invitations.SendEmailAsync(request.MemberId, request.Link); return NoContent(); }
        catch (InvalidOperationException ex) { return BadRequest(new { message = ex.Message }); }
    }
}
