import axios from 'axios';
import type { EventPayload } from '../types/event';
import type { Guest, StatsPayload } from '../types/guest';
import { useEventStore } from '../store/eventStore';

// Use environment variable for API URL or fall back to relative path
const API_BASE_URL = import.meta.env.VITE_API_URL || '/api';

const api = axios.create({
  baseURL: API_BASE_URL,
  headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
  withCredentials: false, // Cross-origin requests
});

// Attach device token from memory on every request.
// No CSRF or session cookies needed — auth is purely via X-Device-Token.
api.interceptors.request.use(config => {
  const token = useEventStore.getState().deviceToken;
  if (token) config.headers['X-Device-Token'] = token;
  return config;
});

// ─── Event ────────────────────────────────────────────────────────────────────

export async function validateEvent(
  eventCode: string,
  deviceName?: string
): Promise<EventPayload> {
  const { data } = await api.post<EventPayload>('checkin/event/validate', {
    event_code: eventCode,
    device_name: deviceName ?? getDeviceName(),
  });
  return data;
}

export async function downloadGuests(): Promise<{ guests: Guest[]; total: number; downloaded_at: string }> {
  const { data } = await api.get('checkin/event/download');
  return data;
}

export async function fetchStats(): Promise<StatsPayload> {
  const { data } = await api.get<StatsPayload>('checkin/event/stats');
  return data;
}

// ─── Check-In ─────────────────────────────────────────────────────────────────

export async function apiScan(qrData: string) {
  const { data } = await api.post('checkin/scan', { qr_data: qrData });
  return data;
}

export async function apiCheckIn(guestId: number) {
  const { data } = await api.post(`checkin/checkin/${guestId}`);
  return data;
}

// ─── Direct Check-In (No Sync Queue) ──────────────────────────────────────────

export async function apiDirectCheckIn(guestId: number, method: 'qr_scan' | 'manual_search' | 'manual_entry') {
  const { data } = await api.post(`checkin/direct-checkin/${guestId}`, { method });
  return data;
}

// ─── Helper ───────────────────────────────────────────────────────────────────

function getDeviceName(): string {
  const ua = navigator.userAgent;
  if (/iPhone/.test(ua)) return 'iPhone';
  if (/iPad/.test(ua)) return 'iPad';
  if (/Android/.test(ua)) return 'Android Device';
  return 'Web Browser';
}

export default api;
