using Microsoft.AspNetCore.Mvc;
using ReportingServices.Shared.Models.PlanningReport;
using ReportingServices.Shared.HelperClasses;

namespace ReportingServices.UI.Controllers
{
    public class PlanningReportController : Controller
    {
        private readonly ILogger<PlanningReportController> _logger;
        private readonly IConfiguration _configuration;
        private readonly string _baseUrl;

        public PlanningReportController(ILogger<PlanningReportController> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
            _baseUrl = _configuration.GetValue<string>("BaseAPIAddress") + "ScrapeDB/";

            _logger.LogInformation("Base API Address: {baseUrl}", _baseUrl);
        }

        public IActionResult Index()
        {
            return View();
        }

        public async Task<IActionResult> WeeklyPartChangesReport(DateTime startDate, DateTime endDate)
        {
            string partChangeUrl = _baseUrl + "PartChanges?startDate=" + startDate.ToString() + "&endDate=" + endDate.ToString();
            string psnwoRunsUrl = _baseUrl + "PSNWO?startDate=" + startDate.ToString() + "&endDate=" + endDate.ToString();

            _logger.LogInformation("Part Change URL: {url}", partChangeUrl);
            _logger.LogInformation("PSN WO Runs URL: {url}", psnwoRunsUrl);

            WeeklyPartChanges weeklyPartChanges = new();

            try
            {
                int numberOfPartChanges = await ApiCaller.GetApi<int>(partChangeUrl);
                List<ReactorPSNWORuns> reactorPSNWORuns = await ApiCaller.GetApi<List<ReactorPSNWORuns>>(psnwoRunsUrl);

                weeklyPartChanges.TotalPartChanges = numberOfPartChanges;
                weeklyPartChanges.StartDate = startDate.ToShortDateString();
                weeklyPartChanges.EndDate = endDate.ToShortDateString();
                weeklyPartChanges.ReactorPSNWORuns = reactorPSNWORuns;
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "Failed to get a response from API calls.");
                RedirectToAction("Error");
            }
            

            return View(weeklyPartChanges);
        }
    }
}
