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

namespace AfRApay.Web.Pages;

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

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

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

		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.");
			}
			user.Nickname = nick!;
			db.Update(user);
		}

		Response.Redirect($"/#{user.Nickname}");
	}
}
