import { Platform } from 'react-native'; const BASE_URL = 'https://api.plyr.fm'; interface AuthState { sessionId: string | null; handle: string | null; displayName: string | null; } let _authState: AuthState = { sessionId: null, handle: null, displayName: null, }; export function getAuthState(): AuthState { return _authState; } export function isAuthenticated(): boolean { return _authState.sessionId !== null; } export async function login(handle: string): Promise { const cleanHandle = handle.trim().replace(/^@/, ''); // On web: redirect to OAuth provider if (Platform.OS === 'web') { const redirectUri = encodeURIComponent('https://cameron.tngl.io/login'); window.location.href = `${BASE_URL}/auth/start?handle=${encodeURIComponent(cleanHandle)}&redirect_uri=${redirectUri}`; // Never returns - page navigates away return new Promise(() => {}); } // Native: would use WebBrowser here throw new Error('Native login not implemented'); } export async function handleCallback(callbackUrl: string): Promise { const url = new URL(callbackUrl); const token = url.searchParams.get('token'); if (!token) { throw new Error('No token in callback URL'); } // Exchange token for session const res = await fetch(`${BASE_URL}/auth/exchange`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }), credentials: 'include', // Important: receives session cookie }); if (!res.ok) { throw new Error(`Token exchange failed: ${res.status}`); } const data = await res.json(); // Store session info _authState = { sessionId: data.session_id || null, handle: data.handle || null, displayName: data.display_name || null, }; return _authState; } export async function logout(): Promise { if (!_authState.sessionId) return; try { await fetch(`${BASE_URL}/auth/logout`, { method: 'POST', headers: { 'Authorization': `Bearer ${_authState.sessionId}`, }, credentials: 'include', }); } catch { // Ignore logout API errors } _authState = { sessionId: null, handle: null, displayName: null }; } export async function getMe(): Promise { if (!_authState.sessionId) throw new Error('Not authenticated'); const res = await fetch(`${BASE_URL}/auth/me`, { headers: { 'Authorization': `Bearer ${_authState.sessionId}`, }, credentials: 'include', }); if (!res.ok) throw new Error(`Get me failed: ${res.status}`); return res.json(); } export async function authedFetch(path: string, init?: RequestInit): Promise { if (!_authState.sessionId) throw new Error('Not authenticated'); return fetch(`${BASE_URL}${path}`, { ...init, headers: { 'Authorization': `Bearer ${_authState.sessionId}`, 'Content-Type': 'application/json', ...init?.headers, }, credentials: 'include', }); }