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

namespace trainav.web.Pages;

public class DeleteModel : PageModel {
	public User AuthorizedUser;

	public void OnGet() {
		if (!Request.Query.ContainsKey("confirm") || Request.Query["confirm"] != "true")
			return;

		using var db  = new Database.DbConn();
		AuthorizedUser = db.Users.FirstOrDefault(p => p.Username == AuthUtil.GetRemoteUser(HttpContext, db));
		var id = int.Parse(Request.Query["id"]);

		switch (Request.Query["item"]) {
			case "trip": {
				var trip = db.Trips.First(p => p.TripId == id);
				if (trip.UserId != AuthorizedUser!.UserId)
					return;

				db.Trips.Delete(p => p.TripId == id);
				db.Legs.Delete(p => p.TripId == id);
				break;
			}
			case "leg": {
				var leg = db.Legs.First(p => p.LegId == id);
				if (leg.UserId != AuthorizedUser!.UserId)
					return;

				var tripid = db.Legs.First(p => p.LegId == id).TripId;

				db.Legs.Delete(p => p.LegId == id);

				if (!db.Legs.Any(p => p.TripId == tripid))
					db.Trips.Delete(p => p.TripId == tripid);
				else if (db.Legs.Where(p => p.TripId == tripid).OrderBy(p => p.DepTime).First().DepTime.EndsWith("placeholder"))
					db.Delete(db.Legs.Where(p => p.TripId == tripid).OrderBy(p => p.DepTime).First());
				else if (db.Legs.Where(p => p.TripId == tripid).OrderByDescending(p => p.DepTime).First().DepTime.EndsWith("placeholder"))
					db.Delete(db.Legs.Where(p => p.TripId == tripid).OrderByDescending(p => p.DepTime).First());

				var failsafe = false;
				foreach (var failsafeleg in db.Legs.Where(p => p.TripId == tripid).OrderBy(p => p.DepTime).ToList())
					if (failsafeleg.DepTime.EndsWith("placeholder")) {
						if (failsafe == false)
							failsafe = true;
						else
							db.Legs.Delete(p => p.LegId == failsafeleg.LegId);
					}
					else {
						failsafe = false;
					}

				break;
			}
		}
	}
}
