import { afterEach, describe, expect, it, vi } from 'vitest';
import { botUsername, friendCodeParam, gameParam, invitationParam, parseStartParam, shareLink, vkShareLink } from './deeplink';

describe('parseStartParam', () => {
  it('classifies game / invitation / friend code', () => {
    expect(parseStartParam('g7c9e6679')).toEqual({ kind: 'game', id: '7c9e6679' });
    expect(parseStartParam('iabc-123')).toEqual({ kind: 'invitation', id: 'abc-123' });
    expect(parseStartParam('f123456')).toEqual({ kind: 'friendCode', code: '123456' });
  });

  it('falls back to the lobby for empty / unknown / value-less params', () => {
    expect(parseStartParam('')).toEqual({ kind: 'lobby' });
    expect(parseStartParam(undefined)).toEqual({ kind: 'lobby' });
    expect(parseStartParam(null)).toEqual({ kind: 'lobby' });
    expect(parseStartParam('x-nope')).toEqual({ kind: 'lobby' });
    expect(parseStartParam('g')).toEqual({ kind: 'lobby' });
  });

  it('round-trips the build helpers', () => {
    expect(parseStartParam(gameParam('id1'))).toEqual({ kind: 'game', id: 'id1' });
    expect(parseStartParam(invitationParam('id2'))).toEqual({ kind: 'invitation', id: 'id2' });
    expect(parseStartParam(friendCodeParam('654321'))).toEqual({ kind: 'friendCode', code: '654321' });
  });
});

describe('shareLink', () => {
  afterEach(() => vi.unstubAllEnvs());

  it('returns null without a configured base', () => {
    vi.stubEnv('VITE_TELEGRAM_LINK', '');
    expect(shareLink('gx')).toBeNull();
  });

  it('wraps a payload in a startapp link', () => {
    vi.stubEnv('VITE_TELEGRAM_LINK', 'https://telegram.me/bot/app');
    expect(shareLink('f123456')).toBe('https://telegram.me/bot/app?startapp=f123456');
  });
});

describe('vkShareLink', () => {
  afterEach(() => vi.unstubAllGlobals());

  it('returns null outside a VK launch (no vk_app_id)', () => {
    vi.stubGlobal('location', { search: '' });
    expect(vkShareLink()).toBeNull();
  });

  it('returns the plain vk.com/app link (VK drops a custom query payload, so the code is not carried)', () => {
    vi.stubGlobal('location', { search: '?vk_app_id=6736218&vk_user_id=1&sign=x' });
    expect(vkShareLink()).toBe('https://vk.com/app6736218');
  });
});

describe('botUsername', () => {
  afterEach(() => vi.unstubAllEnvs());

  it('returns null without a configured base', () => {
    vi.stubEnv('VITE_TELEGRAM_LINK', '');
    expect(botUsername()).toBeNull();
  });

  it('extracts the bot handle from the Mini App link', () => {
    vi.stubEnv('VITE_TELEGRAM_LINK', 'https://telegram.me/bot/app');
    expect(botUsername()).toBe('bot');
  });
});
