using AfRApay.Web.Backend;
using AfRApay.Web.Backend.Tables;
using LinqToDB;
using Microsoft.AspNetCore.Mvc;

namespace AfRApay.Web.Controllers;

[ApiController, Route("/api/card/link")]
public class CardLink : Controller {
	[HttpGet]
	public string Get([FromQuery] string card) {
		var db = new Database.DbConn();
		if (db.Cards.Any(p => p.CardId == card)) {
			return "E:Already registered.";
		}

		var linkFlag = db.Config.FirstOrDefault(p => p.Name == "link");

		if (string.IsNullOrWhiteSpace(linkFlag?.Value)) {
			return "E:No link flag set.";
		}

		var lTimeFlag = db.Config.FirstOrDefault(p => p.Name == "lTime");
		if (string.IsNullOrWhiteSpace(lTimeFlag?.Value)) {
			return "E:No link flag set.";
		}

		if (DateTime.UtcNow - DateTime.Parse(lTimeFlag.Value) > TimeSpan.FromMinutes(5)) {
			return "E:Link expired, try again.";
		}


		var user = db.Users.First(p => p.Id == int.Parse(linkFlag.Value));
		linkFlag.Value = "";

		db.Insert(new Card { CardId = card, UserId = user.Id });
		db.Update(linkFlag);
		return $"S:Reg. -> {user.Nickname}";
	}
}
