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() {
		if (Request.Query.ContainsKey("kiosk")) {
			if (Request.Query["kiosk"] == "true") {
				Response.Cookies.Append("kiosk", "true");
			}
			else {
				Response.Cookies.Delete("kiosk");
			}
		}
	}

	public async void OnPost() {
		await using var db = new DatabaseContext();
		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($"/EditUser/{user.Id}");
				return;
			}

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