using BukiVedi.App.Requests;
using BukiVedi.Shared.Apps;
using BukiVedi.Shared.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace BukiVedi.App.Controllers
{
    [Authorize("authorized")]
    [ApiController]
    [Route("api/tags")]
    public class TagsController
        : BaseController
    {
        private readonly ITagsHandler _handler;
        public TagsController(ITagsHandler handler)
            : base()
        {
            _handler = handler;
        }

        /// <summary>
        /// Список пользовательских тегов
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<string>>> GetUserTags()
        {
            return Ok(await _handler.GetUserTags(OperationContext));
        }

        /// <summary>
        /// Добавление тега для книги
        /// </summary>
        /// <returns>Ok</returns>
        /*[HttpPost]
        public async Task<IActionResult> AppendTag([FromBody] AppendTagRequest request)
        {
            await _handler.AppendTag(request?.BookId!, request?.Name!, OperationContext);
            return Ok();
        }*/

        /// <summary>
        /// Добавление тегов для книги
        /// </summary>
        /// <returns>Ok</returns>
        [HttpPost]
        public async Task<ActionResult<IEnumerable<TagInfo>>> AppendTags([FromBody] AppendTagsRequest request)
        {
            var existsTags = (await _handler.GetBookTags(request.BookId, this.OperationContext))?.Select(t => t.Id)?.ToList();
            var tags = new List<TagInfo>();
            foreach (var name in request.Names)
            {
                var tag = await _handler.AppendTag(request.BookId, name, OperationContext);
                if (tag != null && existsTags != null)
                {
                    existsTags.Remove(tag.Id);
                    tags.Add(tag);
                }
            }
            if (existsTags != null)
            {
                foreach (var id in existsTags)
                {
                    await _handler.RemoveTag(id, OperationContext);
                }
            }
            return Ok(tags);
        }

        /// <summary>
        /// Поиск книг по тегу
        /// </summary>
        /// <returns>Список найденных книг</returns>
        [HttpPost("{id}/books")]
        public async Task<ActionResult<IEnumerable<BookInfo>>> Search([FromRoute] string id)
        {
            return Ok(await _handler.Search(id, OperationContext));
        }

        /// <summary>
        /// Удаление тега для книги
        /// </summary>
        /// <returns>Ok</returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<bool>> RemoveTag([FromRoute] string id)
        {
            return Ok(await _handler.RemoveTag(id, OperationContext));
        }
    }
}
