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

namespace AfRApay.Web.Pages;

public class LinkCardModel : PageModel {
	public void OnGet(int id) {
		using var db        = new Database.DbConn();
		var       linkFlag = db.Config.FirstOrDefault(p => p.Name == "link");
		var       lTimeFlag = db.Config.FirstOrDefault(p => p.Name == "lTime");
		var       user      = db.Users.FirstOrDefault(p => p.Id == id);

		if (user == null) {
			throw new InvalidCredentialException("User does not exist");
		}

		if (lTimeFlag == null) {
			lTimeFlag = new Config { Name = "lTime", Value = DateTime.UtcNow.ToString("s") };
			db.Insert(lTimeFlag);
		}
		else {
			lTimeFlag.Value = DateTime.UtcNow.ToString("s");
			db.Update(lTimeFlag);
		}

		if (linkFlag == null) {
			linkFlag = new Config { Name = "link", Value = id.ToString() };
			db.Insert(linkFlag);
			return;
		}
		
		if (linkFlag.Value.Equals(id.ToString())) {
			return;
		}
		
		linkFlag.Value = id.ToString();
		db.Update(linkFlag);
	}
}
