using System.Data;
using AfRApay.Web.Backend;
using AfRApay.Web.Backend.Tables;
using LinqToDB;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace AfRApay.Web.Pages;

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

	public void OnPost() {
		using var db     = new Database.DbConn();
		if (Request.Form.ContainsKey("nickname") && !string.IsNullOrWhiteSpace(Request.Form["nickname"])) {
			var nick = Request.Form["nickname"];
			if (db.Users.Any(p => p.Nickname == nick)) {
				throw new DuplicateNameException("User with nick already exists.");
			}

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

		throw new ConstraintException("Nickname must not be empty.");
	}
}
