import { buildMessengerBotStartUrl } from '~/composables/useMessengerBotLink';

type MessengerChannel = 'TELEGRAM' | 'MAX';

type MessengerStartResponse = {
  ok: true;
  startToken: string;
  expiresAt: string;
  mode: 'login' | 'connect';
};

type MessengerStartInput = {
  channel: MessengerChannel;
  baseUrl: string;
  email?: string;
  redirectPath?: string;
};

export function useMessengerStart() {
  const pendingChannel = ref<MessengerChannel | null>(null);
  const maxMiniApp = useMaxMiniApp();

  async function openMessengerBot({ channel, baseUrl, email, redirectPath }: MessengerStartInput) {
    pendingChannel.value = channel;

    const payloadPromise = $fetch<MessengerStartResponse>('/api/auth/messenger-start', {
      method: 'POST',
      body: {
        channel,
        email,
        redirectPath,
      },
    });
    payloadPromise.finally(() => {
      pendingChannel.value = null;
    });

    const payload = await payloadPromise;

    const startUrl = buildMessengerBotStartUrl(baseUrl, payload.startToken);
    if (import.meta.client) {
      if (
        channel === 'MAX'
        && maxMiniApp.isAvailable.value
        && startUrl.startsWith('https://max.ru/')
        && typeof maxMiniApp.webApp.value?.openMaxLink === 'function'
      ) {
        maxMiniApp.webApp.value.openMaxLink(startUrl);
      }
      else {
        window.open(startUrl, '_blank', 'noopener,noreferrer');
      }
    }

    return payload;
  }

  return {
    pendingChannel,
    openMessengerBot,
  };
}
