import { apiGet } from './client';
import type { Photo, Album } from '@/types';

export interface PhotoFilters {
  readonly limit?: number;
  readonly since?: string;
  readonly deviceId?: string;
  readonly albumId?: string;
}

export async function fetchPhotos(filters: PhotoFilters = {}): Promise<Photo[]> {
  try {
    const params = new URLSearchParams();
    params.set('limit', String(filters.limit ?? 100));
    if (filters.since) params.set('since', filters.since);
    if (filters.deviceId) params.set('deviceId', filters.deviceId);
    return await apiGet<Photo[]>(`/my/photos?${params}`);
  } catch (err) {
    throw err instanceof Error ? err : new Error('fetchPhotos failed');
  }
}

export async function fetchAlbums(deviceId: string): Promise<Album[]> {
  try {
    return await apiGet<Album[]>(`/my/photos/albums?deviceId=${encodeURIComponent(deviceId)}`);
  } catch (err) {
    throw err instanceof Error ? err : new Error('fetchAlbums failed');
  }
}

export async function fetchPhotosByAlbum(albumId: string, limit = 200): Promise<Photo[]> {
  try {
    const params = new URLSearchParams();
    params.set('limit', String(limit));
    return await apiGet<Photo[]>(`/my/photos/albums/${encodeURIComponent(albumId)}?${params}`);
  } catch (err) {
    throw err instanceof Error ? err : new Error('fetchPhotosByAlbum failed');
  }
}

export type PhotoBlobSize = 'original' | 'thumbnail' | 'preview';

/**
 * Build a URL for the `/my/photos/:id/blob` endpoint with the requested size.
 * Caller must prefix with the configured server URL (handled by <img> when
 * pointing at the same origin, or by api/client for fetches).
 */
export function photoBlobUrl(photoId: string, size: PhotoBlobSize = 'thumbnail'): string {
  return `/my/photos/${encodeURIComponent(photoId)}/blob?size=${size}`;
}
