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 IndexModel : PageModel {
	public void OnGet() { }

	public async void OnPost() {
		await using var db = new DatabaseContext();
		if (Request.Form["action"] == "transaction" && Request.Form.ContainsKey("userId") && Request.Form.ContainsKey("amount")) {
			var userId = int.Parse(Request.Form["userId"].ToString());
			var amount = int.Parse(Request.Form["amount"].ToString());
			var user   = db.Users.First(p => p.Id == userId);
			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($"/#{user.Nickname}");
		}
		else if (Request.Form["action"] == "add_user") {
			if (Request.Form.ContainsKey("nickname") && !string.IsNullOrWhiteSpace(Request.Form["nickname"])) {
				var nick = Request.Form["nickname"];
				if (db.Users.Any(p => p.Nickname == nick.ToString())) {
					Response.Redirect("/ErrorRedirect?redir=%23add_user&message=" + WebUtility.UrlEncode("User with nick already exists."));
					return;
				}

				var user = new User { Nickname = nick.ToString(), Balance = 0 };
				db.Add(user);
				await db.SaveChangesAsync();
				Response.Redirect($"/#{user.Nickname}");
				return;
			}

			Response.Redirect("/ErrorRedirect?redir=%23add_user&message=" + WebUtility.UrlEncode("Nickname must not be empty."));
		}
		else {
			Response.Redirect("/");
		}
	}
}
