namespace Hims.Api.Controllers
{
    using System.IO;
    using System.Linq;
    using System.Threading.Tasks;
    using ClosedXML.Excel;
    using Domain.Services;
    using Microsoft.AspNetCore.Mvc;
    using Models.ExportFilters;
    using Shared.DataFilters;
    using Utilities;

    /// <inheritdoc />
    /// <summary>
    /// The export controller.
    /// </summary>
    [Route("api/export")]
    [Consumes("application/json")]
    public class ExportController : BaseController
    {
        /// <summary>
        /// The export services.
        /// </summary>
        private readonly IExportService exportServices;

        /// <inheritdoc />
        public ExportController(IExportService exportServices) => this.exportServices = exportServices;

        /// <summary>
        /// To export list of payments.
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        /// <remarks>
        /// ### REMARKS ###
        /// The following codes are returned
        /// - 200 - Returns list of payments excel file.
        /// - 500 - Problem with Server side code.
        /// </remarks>
        [HttpPost]
        [Route("payments")]
        [ProducesResponseType(typeof(FileContentResult), 200)]
        [ProducesResponseType(500)]
        public async Task<IActionResult> FetchRolesAsync([FromBody] PaymentExportFilterModel model)
        {
            model = (PaymentExportFilterModel)EmptyFilter.Handler(model);
            var payments = await this.exportServices.FetchPaymentsAsync(model.FromDate, model.ToDate, model.ProviderId, model.PageIndex, model.PageSize);

            const string ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            var dataTable = ListFilter.ToDataTable(payments.ToList(), "Payments");
            using (var wb = new XLWorkbook())
            {
                wb.Worksheets.Add(dataTable);
                using (var stream = new MemoryStream())
                {
                    wb.SaveAs(stream);
                    return this.File(stream.ToArray(), ContentType, model.FileName);
                }
            }
        }
    }
}