using System.Collections.Generic;
using System.Threading.Tasks;
using DiplomovaPrace.Contracts.Customer.Addresses;
using DiplomovaPrace.Contracts.Customer.Addresses.InputModels;
using DiplomovaPrace.Facades.Customer.Addresses;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace DiplomovaPrace.Web.Server.Controllers
{
	[Route("api/address")]
	public class AddressController : ControllerBase
	{
		private readonly IAddressFacade addressFacade;

		public AddressController(IAddressFacade addressFacade)
		{
			this.addressFacade = addressFacade;
		}

		[HttpPost("createUserAddress")]
		[Authorize(Roles = "Uživatel")]
		public async Task<IActionResult> CreateUserAddressAsync([FromBody] CreateAddressIM inputModel)
		{
			int userID = int.Parse(User.Identity.Name);

			UserAddressDto result = await addressFacade.CreateUserAddressAsync(userID, inputModel);

			if (result is not null)
			{
				return Ok(result);
			}

			return BadRequest();
		}

		[HttpDelete("deleteUserAddress/{addressID}")]
		[Authorize(Roles = "Uživatel")]
		public async Task<IActionResult> DeleteUserAddressAsync([FromRoute] int addressID)
		{
			int userID = int.Parse(User.Identity.Name);

			if (userID != 0 && (await addressFacade.DeleteUserAddressAsync(addressID, userID)))
			{
				return Ok();
			}

			return BadRequest();
		}

		[HttpGet("getUserAddresses/{userID}")]
		[Authorize(Roles = "Uživatel")]
		public async Task<List<UserAddressDto>> GetUserAddressesAsync([FromRoute] int userID)
		{
			return await addressFacade.GetUserAddressesAsync(userID);
		}

		[HttpPost("updateUserAddress")]
		[Authorize(Roles = "Uživatel")]
		public async Task<IActionResult> UpdateUserAddressAsync([FromBody] UpdateAddressIM inputModel)
		{
			int userID = int.Parse(User.Identity.Name);

			UserAddressDto result = await addressFacade.UpdateUserAddressAsync(userID, inputModel);

			if (result is not null)
			{
				return Ok(result);
			}

			return BadRequest();
		}
	}
}
