import * as ImagePicker from 'expo-image-picker'

import {downscaleJpeg} from '@/lib/image'

// the one library-photo picker: permission prompt + launch + optional square
// crop + optional downscale. null if the user cancels or denies
export const pickImage = async ({
  crop,
  maxEdge,
}: {
  crop?: 'square'
  maxEdge?: number
} = {}): Promise<string | null> => {
  const perm = await ImagePicker.requestMediaLibraryPermissionsAsync()
  if (!perm.granted) return null

  const res = await ImagePicker.launchImageLibraryAsync({
    mediaTypes: ['images'],
    quality: 1,
    exif: false,
    selectionLimit: 1,
    ...(crop === 'square'
      ? {allowsEditing: true, aspect: [1, 1] as [number, number]}
      : {}),
  })
  const asset = res.canceled ? null : res.assets?.[0]
  if (!asset) return null
  if (maxEdge == null) return asset.uri

  const out = await downscaleJpeg(asset, {maxEdge})
  return out.uri
}

// pick a full library photo (no crop) to extract a crumb from
export const pickShareImage = (): Promise<string | null> =>
  pickImage()
