using Microsoft.AspNetCore.Mvc;
using ReportingServices.Shared.HelperClasses;
using ReportingServices.Shared.Models.ProductionReport;
using ReportingServices.Shared.ViewModels.ProductionReport;
using ReportingServices.UI.Models;

namespace ReportingServices.UI.Controllers;

public class ProductionReportController : Controller
{
    private readonly ILogger<ProductionReportController> _logger;
    private readonly Dictionary<string, string> _filePaths;
    private readonly string _baseDBUrl;

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

        _filePaths = new()
        {
            { "DailyReport", appSettings.DailyReportFilePath },
            { "ToolStateOwners", appSettings.ToolStateOwnerFilePath },
            { "SLL", appSettings.SLLFilePath },
        };

        _logger.LogInformation("Base Database Address: {baseUrl}", _baseDBUrl);
    }

    public IActionResult Index() => View();

    public IActionResult DailyReport()
    {
        try
        {
            DailyReport dailyReport = DailyReportHelper.SetUpDailyReport(_logger, _filePaths, _baseDBUrl);

            return View(dailyReport);
        }
        catch (Exception ex)
        {
            _logger.LogCritical(ex, "Failed to load report");
            return View();
        }
    }

    public IActionResult EditDailyReport()
    {
        ManualReportEntries entries = JsonFileHandler.LoadJSONFile<ManualReportEntries>(_filePaths["DailyReport"]);

        return View(entries);
    }

    [HttpPost]
    public IActionResult EditDailyReport(ManualReportEntries rpt)
    {
        JsonFileHandler.SaveJSONFile(rpt, _filePaths["DailyReport"]);

        return RedirectToAction("DailyReport");
    }

    public IActionResult HoldLotReport()
    {
        List<HoldLot> holdLots = ApiCaller.GetApi<List<HoldLot>>(_baseDBUrl + "GetCurrentHoldLots").Result;

        return View(holdLots);
    }

    public IActionResult NCRReport()
    {
        List<NCR> ncrs = ApiCaller.GetApi<List<NCR>>(_baseDBUrl + "GetCurrentNCRs").Result;

        return View(ncrs);
    }
}