import { t } from '@/i18n';

export const fetchWithTimeout = async (url: string, init: RequestInit = {}, timeout: number = 10000) => {
  const controller = new AbortController();
  const { signal } = controller;

  const timeoutId = setTimeout(() => {
    controller.abort();
  }, timeout);

  try {
    const res = await fetch(url, { ...init, signal });
    return res;
  } catch (err) {
    if ((err as Error).name === 'AbortError') {
      throw new Error(t('common.requestTimedOut'));
    }

    throw err;
  } finally {
    clearTimeout(timeoutId);
  }
};
