import { RequestStatusEnum, type STATUS_CODE } from "@/types/index";
import { useEffect, useState } from "react";

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

export const useAutoStatusSSE = ({
	requestHash,
	enabled = true,
}: {
	requestHash: string;
	enabled?: boolean;
}) => {
	const [status, setStatus] = useState<SSEStatusType>({
		statusCode: undefined,
		status: undefined,
		fulfilAmount: undefined,
		srcTimestamp: undefined, // will be returned after extraction
		destTimestamp: undefined, // will be returned after completion
	});

	useEffect(() => {
		if (requestHash && enabled) {
			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) {
					const baseStatuses = {
						fulfilAmount: data?.fulfilAmount,
						srcTimestamp: data?.srcTimestamp,
						destTimestamp: data?.destTimestamp,
					};
					if (data.event === "RequestFulfilled") {
						setStatus({
							statusCode: RequestStatusEnum.COMPLETED,
							status: "COMPLETED",
							...baseStatuses,
						});
					}
					if (data.event === "RequestExtracted") {
						setStatus({
							statusCode: RequestStatusEnum.EXTRACTED,
							status: "EXTRACTED",
							...baseStatuses,
						});
					}
					if (data.event === "FulfilmentFailed" || data.event === "Expired") {
						setStatus({
							statusCode: data.isRefundPending
								? RequestStatusEnum.REFUND_PENDING
								: RequestStatusEnum.EXPIRED,
							status: data.isRefundPending ? "REFUND_PENDING" : "EXPIRED",
							...baseStatuses,
						});
					}
				}
			};

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

	return status;
};
