import {readAsBlob} from '@/lib/image'
import {pickImage} from '@/lib/pick-image'
import {authedJson} from '@/lib/rpc'

const MIME = 'image/jpeg'

// one jpeg slot on an entity (a crumb's image, a trail's cover, the account
// avatar): pick a downscaled library photo, PUT it, DELETE it — each write
// returning the updated owner parsed by the endpoint's response schema
export const blobEndpoint = <R, T>({
  path,
  schema,
  unwrap,
  maxEdge,
  crop,
}: {
  path: (id: string) => string
  schema: {parse: (value: unknown) => R}
  unwrap: (res: R) => T
  maxEdge: number
  crop?: 'square'
}) => {
  const request = async (id: string, init: RequestInit): Promise<T> =>
    unwrap(await authedJson(path(id), init, schema))
  return {
    // pick + downscale a library photo; null if cancelled/denied
    pick: (): Promise<string | null> => pickImage({crop, maxEdge}),
    upload: async (id: string, uri: string): Promise<T> =>
      request(id, {
        method: 'PUT',
        headers: {'Content-Type': MIME},
        body: await readAsBlob(uri),
      }),
    remove: (id: string): Promise<T> =>
      request(id, {method: 'DELETE'}),
  }
}
