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

namespace ROLAC.API.Controllers;

[ApiController]
[Route("api/monthly-statements")]
[Authorize]
public class MonthlyStatementsController : ControllerBase
{
    private readonly IMonthlyStatementService _svc;
    public MonthlyStatementsController(IMonthlyStatementService svc) => _svc = svc;

    [HttpGet]
    [HasPermission(Modules.MonthlyStatements, PermissionActions.Read)]
    public async Task<IActionResult> GetAll([FromQuery] int? year = null)
        => Ok(await _svc.GetAllAsync(year));

    [HttpGet("{id:int}")]
    [HasPermission(Modules.MonthlyStatements, 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.MonthlyStatements, PermissionActions.Write)]
    public async Task<IActionResult> Create([FromBody] CreateMonthlyStatementRequest r)
    {
        try { return Ok(new { id = await _svc.CreateAsync(r) }); }
        catch (InvalidOperationException ex) { return Conflict(new { message = ex.Message }); }
    }

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

    [HttpPost("{id:int}/finalize")]
    [HasPermission(Modules.MonthlyStatements, PermissionActions.Approve)]
    public async Task<IActionResult> Finalize(int id)
    {
        try { await _svc.FinalizeAsync(id); return NoContent(); }
        catch (KeyNotFoundException) { return NotFound(); }
    }
}
