import { ERROR_CODES, type Result } from "@pkg/result";
import type { FlightTicket, TicketSearchDTO } from "./entities";
import { betterFetch } from "@better-fetch/fetch";
import { getError, Logger } from "@pkg/logger";

export class ScrapedTicketsDataSource {
	scraperUrl: string;
	apiKey: string;

	constructor(scraperUrl: string, apiKey: string) {
		this.scraperUrl = scraperUrl;
		this.apiKey = apiKey;
	}

	async searchForTickets(
		payload: TicketSearchDTO,
	): Promise<Result<FlightTicket[]>> {
		const { data, error } = await betterFetch<Result<FlightTicket[]>>(
			`${this.scraperUrl}/api/v1/tickets/search`,
			{
				method: "POST",
				headers: {
					"Content-Type": "application/json",
					Authorization: `Bearer ${this.apiKey}`,
				},
				body: JSON.stringify(payload),
			},
		);

		if (error) {
			return {
				error: getError(
					{
						code: ERROR_CODES.NETWORK_ERROR,
						message: "Failed to search for tickets",
						detail: "Could not fetch tickets for the given payload",
						userHint: "Please try again later",
						error: error,
						actionable: false,
					},
					JSON.stringify(error, null, 4),
				),
			};
		}

		Logger.info(`Returning ${data.data?.length} tickets`);

		return { data: data.data ?? [] };
	}
}
