using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using POCDistance.Models;
using POCDistance.Service;
using System;
using System.Net;

namespace POCDistance.Controllers
{
    [EnableCors(SecurityPolicy.SiteCorsPolicy)]
    [ApiController]
    [Route("api/[controller]")]
    public class DistanceController : ControllerBase
    {
        private readonly ILogger<DistanceController> _logger;
        private readonly ILocationService _locationService;
        public ErrorModel errorModel;

        public DistanceController(ILogger<DistanceController> logger, ILocationService locationService)
        {
            _logger = logger;
            _locationService = locationService;
        }

        [Route("GetDistance")]
        [HttpGet]
        public ActionResult GetDistance(string travelFrom, string travelTo)
        {
            var vResult = new ErrorModel();

            var model = _locationService.GetDistanceByZipCode(travelFrom, travelTo);

            if (!string.IsNullOrEmpty(model.Distance))
            {
                return Ok(model);
            }
            else
            {
                vResult.Status = Convert.ToInt32(HttpStatusCode.BadRequest);
                vResult.Message = "Postal code(s) not found!";
                return BadRequest(vResult);
            }
        }

        [Route("GetZipCode")]
        [HttpGet]
        public ActionResult GetZipCode(string zipCode)
        {
            var vResult = new ErrorModel();           

            var model = _locationService.GetManyByZipCode(zipCode);

            if (model.Count > 0)
            {
                return Ok(model);
            }
            else
            {
                vResult.Status = Convert.ToInt32(HttpStatusCode.BadRequest);
                vResult.Message = "Zip code not found";
                return BadRequest(vResult);
            }
        }        
    }
}