using System;
using Application;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Api.Controllers
{
  [Route("api/links")]
  [ApiController]
  public class LinksController : ControllerBase
  {
    private readonly LinkService _linkService;
    private readonly CommentService _commentService;

    public LinksController(LinkService linkService, CommentService commentService)
    {
      _linkService = linkService;
      _commentService = commentService;
    }

    /// <summary>
    /// Récupère la liste liste des derniers liens publiés.
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public LinkDTO[] GetLatest()
    {
      return _linkService.GetAllLinks();
    }

    /// <summary>
    /// Récupère les détails d'un lien.
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id:guid}")]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    [ProducesResponseType(StatusCodes.Status200OK)]
    public LinkDTO GetById(Guid id)
    {
      return _linkService.GetLinkById(id);
    }

    /// <summary>
    /// Récupère tous les commentaires associés à un lien.
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id:guid}/comments")]
    public CommentDTO[] Comments(Guid id)
    {
      return _commentService.GetAllLinkComments(id);
    }

    /// <summary>
    /// Permet de publier un nouveau lien sur la plateforme.
    /// </summary>
    /// <param name="cmd"></param>
    /// <returns></returns>
    [HttpPost]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    [ProducesResponseType(StatusCodes.Status201Created)]
    public IActionResult Create(PublishLinkCommand cmd)
    {
      var linkId = _linkService.PublishLink(cmd);

      return CreatedAtAction(nameof(GetById), new { id = linkId }, null);
    }
  }
}