import { trpcApiStore } from "$lib/stores/api";
import type { FullOrderModel } from "@pkg/logic/domains/order/data/entities";
import { toast } from "svelte-sonner";
import { get } from "svelte/store";

export class TrackViewModel {
	uid = $state("");
	loading = $state(false);
	bookingData = $state<FullOrderModel | undefined>(undefined);
	error = $state<string | null>(null);

	async searchBooking() {
		if (!this.uid) {
			this.error = "Please enter a PNR number";
			return;
		}

		const api = get(trpcApiStore);
		if (!api) {
			return;
		}

		try {
			this.loading = true;
			this.error = null;

			const result = await api.order.findByUID.query({ uid: this.uid });

			if (result.error) {
				this.error = result.error.message;
				toast.error(result.error.message, {
					description: result.error.userHint,
				});
				this.bookingData = undefined;
			} else {
				this.bookingData = result.data;
			}
		} catch (e) {
			this.error = "Failed to fetch booking details";
			this.bookingData = undefined;
		} finally {
			this.loading = false;
		}
	}
}

export const trackVM = new TrackViewModel();
