using LinqToDB;
using Microsoft.AspNetCore.Mvc;
using zotanpw_web.database;
using zotanpw_web.database.Tables;

namespace zotanpw_web.Travelynx;

[ApiController, Route("/travelynx")]
public class Travelynx : Controller {
	private static readonly string TravelynxSecret = System.IO.File.ReadAllLines(".bearer_token")[0];

	[HttpPost]
	public TravelynxInfo Update([FromBody] WebhookRequest rq) {
		var token = Request.Headers.Authorization;
		if (token == TravelynxSecret) {
			var db = new Database.DbConn();
			if (!db.TravelynxInfo.Any())
				db.InsertWithIdentity(new TravelynxInfo { CheckedIn = false });

			var status = db.TravelynxInfo.First();
			status.CheckedIn   = rq.Status!.CheckedIn;
			status.Train       = $"{rq.Status.Train?.Type} {rq.Status.Train?.No}";
			status.Destination = rq.Status.ToStation?.Name;
			db.Update(status);
			return status;
		}

		Response.StatusCode = 403;
		return null!;
	}
}
