import { createTRPCRouter } from "$lib/trpc/t";
import { z } from "zod";
import { publicProcedure } from "$lib/server/trpc/t";
import { getTC } from "./controller";
import { Logger } from "@pkg/logger";
import {
	flightPriceDetailsModel,
	flightTicketModel,
	ticketSearchPayloadModel,
} from "../data/entities/index";
import type { Result } from "@pkg/result";
import { getCKUseCases } from "$lib/domains/ckflow/domain/usecases";
import { CouponRepository } from "@pkg/logic/domains/coupon/repository";
import { db } from "@pkg/db";

export const ticketRouter = createTRPCRouter({
	searchAirports: publicProcedure
		.input(z.object({ query: z.string() }))
		.query(async ({ input }) => {
			const { query } = input;
			const tc = getTC();
			Logger.info(`Fetching airports with query: ${query}`);
			return await tc.searchAirports(query);
		}),

	ping: publicProcedure
		.input(z.object({ tid: z.number(), refOIds: z.array(z.number()) }))
		.query(async ({ input }) => {
			console.log("Pinged");
			console.log(input);
			const ckflowUC = getCKUseCases();
			const out = await ckflowUC.areCheckoutAlreadyLiveForOrder(
				input.refOIds,
			);
			return { data: out } as Result<boolean>;
		}),

	getAirportByCode: publicProcedure
		.input(z.object({ code: z.string() }))
		.query(async ({ input }) => {
			return await getTC().getAirportByCode(input.code);
		}),

	searchTickets: publicProcedure
		.input(ticketSearchPayloadModel)
		.query(async ({ input }) => {
			const cr = new CouponRepository(db);
			const coupon = await cr.getBestActiveCoupon();
			Logger.info(`Got coupon? :: ${coupon.data?.code}`);
			return getTC().searchForTickets(input, coupon.data);
		}),

	cacheTicket: publicProcedure
		.input(z.object({ sid: z.string(), payload: flightTicketModel }))
		.mutation(async ({ input }) => {
			return await getTC().cacheTicket(input.sid, input.payload);
		}),

	updateTicketPrices: publicProcedure
		.input(z.object({ tid: z.number(), payload: flightPriceDetailsModel }))
		.mutation(async ({ input }) => {
			return await getTC().updateTicketPrices(input.tid, input.payload);
		}),

	getTicketById: publicProcedure
		.input(z.object({ id: z.number() }))
		.query(async ({ input }) => {
			return await getTC().getTicketById(input.id);
		}),
});
