using System.Net;
using AfRApay.Web.Backend.Database;
using AfRApay.Web.Backend.Database.Tables;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace AfRApay.Web.Pages;

public class EditUserModel : PageModel {
	public void OnGet() { }

	public async void OnPost() {
		await using var db     = new DatabaseContext();
		var             userId = long.Parse(RouteData.Values["id"]!.ToString()!);
		var             user   = db.Users.First(p => p.Id == userId);

		if (Request.Form["action"] == "delete") {
			db.Remove(user);
			await db.SaveChangesAsync();
			Response.Redirect("/");
			return;
		}

		if (Request.Form["action"] == "deleteCard" && Request.Form.ContainsKey("cardId")) {
			var card = db.Cards.First(p => p.Id == Request.Form["cardId"].ToString());
			db.Remove(card);
			await db.SaveChangesAsync();
			Response.Redirect($"/EditUser/{userId}");
			return;
		}

		if (Request.Form["action"] == "linkCard") {
			var linkFlag  = db.Config.FirstOrDefault(p => p.Name == "link");
			var lTimeFlag = db.Config.FirstOrDefault(p => p.Name == "lTime");

			Response.Redirect($"/EditUser/{userId}");

			if (lTimeFlag == null) {
				lTimeFlag = new Config { Name = "lTime", Value = DateTime.UtcNow.ToString("s") };
				db.Add(lTimeFlag);
				await db.SaveChangesAsync();
			}
			else {
				lTimeFlag.Value = DateTime.UtcNow.ToString("s");
				await db.SaveChangesAsync();
			}

			if (linkFlag == null) {
				linkFlag = new Config { Name = "link", Value = user.Id.ToString() };
				db.Add(linkFlag);
				await db.SaveChangesAsync();
				return;
			}

			if (linkFlag.Value.Equals(user.Id.ToString())) {
				return;
			}

			linkFlag.Value = user.Id.ToString();
			await db.SaveChangesAsync();
			return;
		}

		if (Request.Form["action"] == "save"
		 && Request.Form.ContainsKey("nickname")
		 && Request.Form.ContainsKey("balance")
		 && !string.IsNullOrWhiteSpace(Request.Form["nickname"])
		 && !string.IsNullOrWhiteSpace(Request.Form["balance"])) {
			var nick    = Request.Form["nickname"].ToString();
			var balance = decimal.Parse(Request.Form["balance"]!);
			if (db.Users.Any(p => p.Nickname == nick && p.Id != userId)) {
				Response.Redirect($"/ErrorRedirect?redir=EditUser/{userId}&message=" + WebUtility.UrlEncode("User with nick already exists."));
				return;
			}

			user.Nickname = nick;
			user.Balance  = (long)(balance * 100);
			await db.SaveChangesAsync();
		}

		if (Request.Form.ContainsKey("amount")) {
			var amount = int.Parse(Request.Form["amount"].ToString());
			switch (user.Balance + amount) {
				case < -9999:
					Response.Redirect("/ErrorRedirect?message=" + WebUtility.UrlEncode("Balance too low!"));
					return;
				case > 99999:
					Response.Redirect("/ErrorRedirect?message=" + WebUtility.UrlEncode("Balance too high!"));
					return;
			}

			user.Balance += amount;
			await db.SaveChangesAsync();
			Response.Redirect($"/EditUser/{user.Id}");
		}
		else {
			Response.Redirect($"/");
		}
	}

	public enum CardDisplayType {
		Normal               = 1,
		LinkPlaceholder      = 2,
		DeletionConfirmation = 3
	}
}
