using Microsoft.AspNetCore.Mvc;
using eSPJ.Services;

namespace eSPJ.Controllers.SpjDriverUpstController
{
    [Route("upst/history")]
    public class HistoryController : Controller
    {
        private readonly HistoryService _historyService;

        public HistoryController(HistoryService historyService)
        {
            _historyService = historyService;
        }

        [HttpGet("")]
        public IActionResult Index()
        {
            return View("~/Views/Admin/Transport/SpjDriverUpst/History/Index.cshtml");
        }

        [HttpGet("api")]
        public async Task<IActionResult> GetHistory([FromQuery] string? fromDate = null, [FromQuery] string? toDate = null, [FromQuery] int page = 1, [FromQuery] int pageSize = 5)
        {
            DateOnly? parsedFromDate = null;
            DateOnly? parsedToDate = null;

            if (!string.IsNullOrWhiteSpace(fromDate) && DateOnly.TryParse(fromDate, out var from))
            {
                parsedFromDate = from;
            }

            if (!string.IsNullOrWhiteSpace(toDate) && DateOnly.TryParse(toDate, out var to))
            {
                parsedToDate = to;
            }

            var result = await _historyService.GetUpstHistoryAsync(parsedFromDate, parsedToDate, page, pageSize <= 0 ? 5 : pageSize);
            return Ok(result);
        }

        [HttpGet("details/{id}")]
        public IActionResult Details(int id)
        {
            ViewData["Id"] = id;
            return View("~/Views/Admin/Transport/SpjDriverUpst/History/Details.cshtml");
        }
    }
}
