using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Serilog;
using Landmark.OLA.Models.Addresses;
using Landmark.OLA.Models.Addresses.Validators;
using Landmark.OLA.Models.Vendor;
namespace Landmark.OLA.Application.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AddressValidationController : ControllerBase
{
private readonly IUspsVendorClient UspsVendor;
public AddressValidationController(IUspsVendorClient uspsVendor)
{
UspsVendor = uspsVendor;
}
///
/// Use to correct a postal address
///
///
/// Returns a service corrected postal address, given a postal address.
/// Cookies: None required or set.
/// Security: None required or provided.
///
[HttpPost]
[ProducesResponseType(typeof(Address), 201)]
[ProducesResponseType(204)]
[ProducesResponseType(typeof(ModelStateDictionary), 400)]
public async Task Post([FromBody] Address address)
{
try
{
var validator = new AddressValidator();
var validatorResult = validator.Validate(address);
if (!validatorResult.IsValid)
{
foreach (var error in validatorResult.Errors)
{
ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
}
return BadRequest(ModelState);
}
var result = await UspsVendor.CompareAddress(address);
return Ok(result);
}
catch (TimeoutException te)
{
Log.Error(te.Message);
return BadRequest("The time taken to submit the address to the vendor has exceeded the configured timeout length.");
}
catch (ArgumentException )
{
// This happens when the address is valid in form, but not found.
return StatusCode(204);
}
catch (Exception e)
{
Log.Error(e.Message);
return StatusCode(204);
}
}
}
}