import { useEffect, useRef } from 'react';
import { Spinner } from '@incode/ui';
import { sleep } from '@incode/utils';
import processId from '@incodetech/welcome/processId';

type ProcessIdProps = {
  goNext: () => void;
  token: string;
};
const ProcessId = ({ goNext, token }: ProcessIdProps) => {
  const alreadyCalledRef = useRef(false);

  useEffect(() => {
    if (alreadyCalledRef.current) {
      return;
    }
    alreadyCalledRef.current = true;
    const dataPromise = processId({
      token,
    });

    const sleepPromise = sleep(3000);

    Promise.all([dataPromise, sleepPromise])
      .then(() => {
        goNext();
      })
      .catch(() => {
        goNext(); // ID already processed, we can continue
      });
  }, [goNext, token]);

  return <Spinner />;
};

export default ProcessId;
