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

namespace ReportingServices.UI.Controllers;

public class PlanningReportController : Controller
{
    private readonly ILogger<PlanningReportController> _logger;
    private readonly string _baseUrl;

    public PlanningReportController(ILogger<PlanningReportController> logger, AppSettings appSettings)
    {
        _logger = logger;
        _baseUrl = appSettings.BaseAPIAddress;

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

    public IActionResult Index() => 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);
    }
}