using System.Linq;
using bahnplan.web.database;
using bahnplan.web.database.Tables;
using LinqToDB;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace bahnplan.web.Pages {
	public class RegisterModel : PageModel {
		public void OnPost() {
			if (!Request.HasFormContentType
				|| string.IsNullOrWhiteSpace(Request.Form["user"])
				|| string.IsNullOrWhiteSpace(Request.Form["pass"])
				|| string.IsNullOrWhiteSpace(Request.Form["code"]))
				return;

			if (Request.Form["code"] != System.IO.File.ReadAllLines("regkey.txt")[0])
				return;

			using var db   = new Database.DbConn();
			var       user = db.Users.FirstOrDefault(p => p.Username == Request.Form["user"].ToString());
			if (user != null)
				return; //user already exists

			var uid = db.InsertWithInt32Identity(new User {Username = Request.Form["user"].ToString(), Password = Request.Form["pass"].ToString().Sha256()});

			HttpContext.Session.SetString("uid", uid.ToString());
			HttpContext.Session.SetString("authorized", "true");
		}
	}
}