using collAnon.Pub.Shared;
using drinkMe.Server.Models;
using drinkMe.Server.Services.Interfaces;
using drinkMe.Shared;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace drinkMe.Server.Controllers
{
	[ApiController]
	[Route("api/[controller]/[action]")]
	public class DrinksController : ControllerBase
	{
		readonly IDataService DataService;
		readonly IPaymentService PaymentService;

		public DrinksController(IDataService dataService, IPaymentService paymentService)
		{
			DataService = dataService;
			PaymentService = paymentService;
		}

		[HttpGet]
		public async Task<IActionResult> IsValidDiscountCode([FromQuery] string code)
		{
			try
			{
				var validationResult = await DataService.IsValidDiscountCode(code);
				if (!validationResult.IsValid)
					return StatusCode(validationResult.StatusCode, validationResult);

				var validationData = validationResult.Data as DiscountCode;
				var resultData = new DiscountCodeViewModel
				{
					Code = validationData.Code,
					ApplicableProducts = validationData.ApplicableProducts,
					DiscountPercentage = validationData.DiscountPercentage
				};

				return Ok(resultData);
			}
			catch (Exception ex)
			{
				return BadRequest(new WebResult().Invalidate($"Error at ${nameof(IsValidDiscountCode)}", default, ex));
			}
		}

		[HttpGet]
		public async Task<IActionResult> GetDrinks()
		{
			try
			{
				var drinks = DataService.GetDrinks();
				if (drinks.Count == 0)
					return NotFound(new WebResult().Invalidate("No drinks available.", StatusCodes.Status404NotFound));

				var viewDrinks = drinks.Select(d => new DrinkViewModel
				{
					Id = d.Id,
					Name = d.Name,
					Description = d.Description,
					Price = d.Price,
					PictureName = d.PictureName
				}).ToArray();

				return Ok(viewDrinks);
			}
			catch (Exception ex)
			{
				return BadRequest(new WebResult().Invalidate($"Error at ${nameof(GetDrinks)}", default, ex));
			}
		}

		[HttpPost]
		public async Task<IActionResult> Pay(PurchaseCart purchaseCart)
		{
			try
			{
				var successfulPayment = await PaymentService.Pay(purchaseCart);

				if (!successfulPayment)
					return BadRequest(new WebResult().Invalidate("Payment failed.", StatusCodes.Status400BadRequest));

				return Ok();
			}
			catch (Exception ex)
			{
				return BadRequest(new WebResult().Invalidate($"Error at ${nameof(Pay)}", default, ex));
			}
		}
	}
}
