/**
 * Los 8 endpoints de la API (ver docs/openapi.yaml y brief §3), tipados.
 */
import { request } from './client';
import {
  Bundle,
  LoginRequest,
  LoginResponse,
  MediaParentEntity,
  MediaUploadResult,
  Operation,
  Project,
  SyncResponse,
  Template,
  User,
} from './types';

// --- Auth ---

export function login(payload: LoginRequest): Promise<LoginResponse> {
  return request<LoginResponse>('/login', { method: 'POST', json: payload, auth: false });
}

export function me(): Promise<{ user: User }> {
  return request<{ user: User }>('/me');
}

export function logout(): Promise<unknown> {
  return request('/logout', { method: 'POST' });
}

// --- PULL ---

export function listProjects(): Promise<{ data?: Project[] } | Project[]> {
  return request('/projects');
}

/**
 * Bundle del proyecto. Sin `since` → snapshot completo; con `since` → delta
 * + tombstones. El `+` del offset horario se URL-encodea en el cliente HTTP.
 */
export function getBundle(projectId: number, since?: string): Promise<Bundle> {
  return request<Bundle>(`/projects/${projectId}/bundle`, {
    query: since ? { since } : undefined,
  });
}

export function getTemplates(since?: string): Promise<{ data?: Template[] } | Template[]> {
  return request('/templates', { query: since ? { since } : undefined });
}

// --- PUSH ---

export function sync(operations: Operation[]): Promise<SyncResponse> {
  return request<SyncResponse>('/sync', { method: 'POST', json: { operations } });
}

// --- Media ---

export interface MediaUploadInput {
  uuid: string;
  parentEntity: MediaParentEntity;
  parentId: number;
  /** URI local del fichero (file:// ...). */
  fileUri: string;
  fileName?: string;
  mimeType?: string;
  category?: 'image' | 'document' | 'other';
  description?: string;
}

export function uploadMedia(input: MediaUploadInput): Promise<MediaUploadResult> {
  const form = new FormData();
  form.append('uuid', input.uuid);
  form.append('parent_entity', input.parentEntity);
  form.append('parent_id', String(input.parentId));
  if (input.category) form.append('category', input.category);
  if (input.description) form.append('description', input.description);
  // En React Native, FormData acepta { uri, name, type } para ficheros.
  form.append('file', {
    uri: input.fileUri,
    name: input.fileName ?? input.fileUri.split('/').pop() ?? 'upload',
    type: input.mimeType ?? 'application/octet-stream',
  } as unknown as Blob);

  return request<MediaUploadResult>('/media', { method: 'POST', form });
}
