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/books")]
    public class BooksController
        : BaseController
    {
        private readonly IBooksHandler _handler;
        public BooksController(IBooksHandler handler)
            : base()
        {
            _handler = handler;
        }

        #region SEARCH
        /// <summary>
        /// Поиск книг по запросу
        /// </summary>
        /// <param name="request">Поисковый запрос</param>
        /// <returns>Список найденных книг</returns>
        [HttpPost("search")]
        public async Task<ActionResult<IEnumerable<BookInfo>>> Search([FromBody] QueryRequest request)
        {
            string tag = null;
            if (Request.Query.TryGetValue("tag", out var sv))
            {
                tag = sv.ToString();
            }
            return Ok(await _handler.Search(request.Query, tag, OperationContext));
        }

        #endregion

        /// <summary>
        /// Добавление книги в избранное
        /// </summary>
        /// <param name="id">Идентификатор книги</param>
        /// <returns>Ok</returns>
        [HttpPost("{id}/favorite")]
        public async Task<IActionResult> AddToFavorite([FromRoute] string id)
        {
            await _handler.AddToFavorite(id, OperationContext);
            return Ok();
        }

        /// <summary>
        /// Добавление авторов книги в избранное
        /// </summary>
        /// <param name="id">Идентификатор книги</param>
        /// <returns>Ok</returns>
        [HttpPost("{id}/authors/favorite")]
        public async Task<IActionResult> AddAuthorsToFavorite([FromRoute] string id)
        {
            await _handler.AddAuthorsToFavorite(id, OperationContext);
            return Ok();
        }

        /// <summary>
        /// Добавление книги в игнор
        /// </summary>
        /// <param name="id">Идентификатор книги</param>
        /// <returns>Ok</returns>
        [HttpPost("{id}/block")]
        public async Task<IActionResult> BlockBook([FromRoute] string id)
        {
            await _handler.BlockBook(id, OperationContext);
            return Ok();
        }

        /// <summary>
        /// Добавление авторов книги в игнор
        /// </summary>
        /// <param name="id">Идентификатор книги, чьих авторов нужно заблокировать</param>
        /// <returns>Ok</returns>
        [HttpPost("{id}/author/block")]
        public async Task<ActionResult> BlockBookAuthor([FromRoute] string id)
        {
            await _handler.BlockBookAuthor(id, OperationContext);
            return Ok();
        }

        /// <summary>
        /// Добавление книги в очередь на чтение
        /// </summary>
        /// <param name="id">Идентификатор книги</param>
        /// <returns>Ok</returns>
        [HttpPost("{id}/read")]
        public async Task<IActionResult> AddBookToReadingQueue([FromRoute] string id)
        {
            await _handler.AddBookToReadingQueue(id, OperationContext);
            return Ok();
        }

        /// <summary>
        /// Загрузка файла с книгой
        /// </summary>
        /// <param name="id">Идентификатор книги</param>
        /// <returns>Файл</returns>
        [HttpGet("download/{id}")]
        public async Task<IActionResult> GetBlobDownload([FromRoute] string id)
        {
            var (name, content) = await _handler.GetBlobData(id, OperationContext);
            var contentType = "APPLICATION/octet-stream";
            var fileName = $"{name}.fb2";
            return File(content, contentType, fileName);
        }

        /// <summary>
        /// Удаление книги из избранного
        /// </summary>
        /// <returns>Ok</returns>
        [HttpDelete("{id}/favorite")]
        public async Task<ActionResult<bool>> RemoveFromFavorites([FromRoute] string id)
        {
            await _handler.RemoveFromFavorite(id, OperationContext);
            return Ok();
        }

        /// <summary>
        /// Удаление книги из заблокированных
        /// </summary>
        /// <returns>Ok</returns>
        [HttpDelete("{id}/block")]
        public async Task<ActionResult<bool>> Unblock([FromRoute] string id)
        {
            await _handler.UnblockBook(id, OperationContext);
            return Ok();
        }

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