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

namespace ROLAC.API.Controllers;

[ApiController]
[Route("api/givings")]
[Authorize]
public class GivingsController : ControllerBase
{
    private readonly IGivingService _svc;
    public GivingsController(IGivingService svc) => _svc = svc;

    [HttpGet]
    [HasPermission(Modules.Givings, PermissionActions.Read)]
    public async Task<IActionResult> GetPaged(
        [FromQuery] int page = 1, [FromQuery] int pageSize = 20,
        [FromQuery] string? search = null, [FromQuery] int? categoryId = null,
        [FromQuery] DateOnly? from = null, [FromQuery] DateOnly? to = null)
        => Ok(await _svc.GetPagedAsync(page, pageSize, search, categoryId, from, to));

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

    [HttpPost]
    [HasPermission(Modules.Givings, PermissionActions.Write)]
    public async Task<IActionResult> Create([FromBody] CreateGivingRequest request)
    {
        var id = await _svc.CreateAsync(request);
        return CreatedAtAction(nameof(GetById), new { id }, new { id });
    }

    [HttpPut("{id:int}")]
    [HasPermission(Modules.Givings, PermissionActions.Write)]
    public async Task<IActionResult> Update(int id, [FromBody] UpdateGivingRequest request)
    {
        try   { await _svc.UpdateAsync(id, request); return NoContent(); }
        catch (KeyNotFoundException)     { return NotFound(); }
        catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
    }

    [HttpDelete("{id:int}")]
    [HasPermission(Modules.Givings, PermissionActions.Delete)]
    public async Task<IActionResult> Delete(int id)
    {
        try   { await _svc.DeleteAsync(id); return NoContent(); }
        catch (KeyNotFoundException)     { return NotFound(); }
        catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
    }
}
