import { useEffect, useState } from "react";
import { RequestStatusEnum, type STATUS_CODE } from "./useRequestStatus";

type RequestStatusType = {
	statusCode: STATUS_CODE | undefined;
	status: keyof typeof RequestStatusEnum | undefined;
	fulfilAmount: string | undefined;
	srcTimestamp: number | undefined;
	destTimestamp: number | undefined;
};

export const useRequestStatusSSE = ({
	requestHash,
}: { requestHash: string }) => {
	const [status, setStatus] = useState<RequestStatusType>({
		statusCode: undefined,
		status: undefined,
		fulfilAmount: undefined,
		srcTimestamp: undefined, // will be returned after extraction
		destTimestamp: undefined, // will be returned after completion
	});

	useEffect(() => {
		if (requestHash) {
			// biome-ignore format:
			const sseUrl =  `https://sse.socket.tech/request-status?requestHash=${requestHash}`

			const newEventSource = new EventSource(sseUrl);

			newEventSource.onmessage = (event) => {
				const data = JSON.parse(event.data);
				if (data.event) {
					if (data.event === "RequestFulfilled") {
						setStatus({
							statusCode: RequestStatusEnum.FULFILLED,
							status: "FULFILLED",
							fulfilAmount: data?.fulfilAmount,
							srcTimestamp: data?.srcTimestamp,
							destTimestamp: data?.destTimestamp,
						});
					} else if (data.event === "RequestExtracted") {
						setStatus({
							statusCode: RequestStatusEnum.EXTRACTED,
							status: "EXTRACTED",
							fulfilAmount: data?.fulfilAmount,
							srcTimestamp: data?.srcTimestamp,
							destTimestamp: data?.destTimestamp,
						});
					}
				}
			};

			return () => {
				newEventSource.close();
			};
		}
	}, [requestHash]);

	return status;
};
