using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/v1/sites")]
[Produces("application/json")]
[Authorize]
public class SitesController : ControllerBase
{
    private readonly ISiteService _sites;

    public SitesController(ISiteService sites) => _sites = sites;

    [HttpPost]
    [AuthorizePermission(ClinicalPermissions.UsersAdmin)]
    [ProducesResponseType(typeof(ApiResponse<SiteResponse>), StatusCodes.Status201Created)]
    public async Task<IActionResult> Create([FromBody] CreateSiteRequest req)
    {
        var site = await _sites.CreateAsync(req);
        return StatusCode(201, ApiResponse<SiteResponse>.Created(MapSite(site)));
    }

    [HttpGet]
    [AuthorizePermission(ClinicalPermissions.UsersAdmin)]
    public async Task<IActionResult> List()
    {
        var sites = await _sites.ListAsync();
        return Ok(ApiResponse<List<SiteResponse>>.Ok(sites.Select(MapSite).ToList()));
    }

    [HttpGet("{siteId:guid}")]
    [AuthorizePermission(ClinicalPermissions.UsersAdmin)]
    public async Task<IActionResult> Get(Guid siteId)
    {
        var site = await _sites.GetByIdAsync(siteId);
        return Ok(ApiResponse<SiteResponse>.Ok(MapSite(site)));
    }

    private static SiteResponse MapSite(ClinicalSite s) =>
        new(s.Id, s.SiteCode, s.Name, s.Address, s.Active, s.CreatedAt);
}