import { Platform } from 'react-native';
import { RecordModel } from 'pocketbase';
import { pb } from './pocketbase';

export function getPhotoUrl(record: RecordModel): string | null {
  if (!record.photo) return null;
  return pb.files.getURL(record, record.photo as string);
}

export async function buildPhotoFormData(
  key: string,
  uri: string,
  formData?: FormData
): Promise<FormData> {
  const fd = formData ?? new FormData();
  if (Platform.OS === 'web') {
    const res = await fetch(uri);
    const blob = await res.blob();
    fd.append(key, blob, 'photo.jpg');
  } else {
    fd.append(key, { uri, name: 'photo.jpg', type: 'image/jpeg' } as any);
  }
  return fd;
}

export async function compressPhoto(uri: string): Promise<string> {
  if (Platform.OS === 'web') return uri;
  const { manipulateAsync, SaveFormat } = await import('expo-image-manipulator');
  const result = await manipulateAsync(uri, [{ resize: { width: 800 } }], {
    compress: 0.7,
    format: SaveFormat.JPEG,
  });
  return result.uri;
}
