import { getDeviceId } from '../lib/device';

export type PendingUpload = {
  id: number;
  status: 'pending' | 'approved' | 'rejected';
  created_at?: string | null;
  thumbnail_url?: string | null;
  full_url?: string | null;
};

type PendingUploadsResponse = {
  data: PendingUpload[];
  meta?: {
    total_count?: number;
  };
};

async function handleResponse<T>(response: Response): Promise<T> {
  const data = await response.json().catch(() => null);

  if (!response.ok) {
    const errorPayload = data as { error?: { message?: string; code?: unknown } } | null;
    const error = new Error(errorPayload?.error?.message ?? 'Request failed') as Error & { code?: unknown };
    error.code = errorPayload?.error?.code ?? response.status;
    throw error;
  }

  return data as T;
}

export async function fetchPendingUploadsSummary(
  token: string,
  limit = 12
): Promise<{ items: PendingUpload[]; totalCount: number }> {
  const params = new URLSearchParams();
  params.set('limit', String(limit));

  const response = await fetch(`/api/v1/events/${encodeURIComponent(token)}/pending-photos?${params.toString()}`, {
    headers: {
      'Accept': 'application/json',
      'X-Device-Id': getDeviceId(),
    },
    credentials: 'omit',
  });

  const payload = await handleResponse<PendingUploadsResponse>(response);

  return {
    items: payload.data ?? [],
    totalCount: payload.meta?.total_count ?? (payload.data?.length ?? 0),
  };
}
