import * as ImagePicker from 'expo-image-picker'
import { Linking, Platform } from 'react-native'
import { disclose } from 'src/state/permissionDisclosure'

/** Kind of permission being gated — surfaces the right label in the screen. */
export type PermissionKind = 'camera' | 'microphone' | 'mediaLibrary'

export class PermissionDeniedError extends Error {
  constructor(public kind: PermissionKind) {
    super(`${kind} permission denied`)
    this.name = 'PermissionDeniedError'
  }
}

/** Imperative helper. Most screens should use the hook forms; this exists for
 *  pipelines that run before a component renders (e.g. pre-requesting the
 *  media-library permission before iOS pops its dialog mid-pick for videos). */
export async function ensureMediaLibraryPermission(): Promise<boolean> {
  const cur = await ImagePicker.getMediaLibraryPermissionsAsync()
  if (cur.granted) return true
  if (!cur.canAskAgain) throw new PermissionDeniedError('mediaLibrary')
  const next = await ImagePicker.requestMediaLibraryPermissionsAsync()
  if (next.granted) return true
  throw new PermissionDeniedError('mediaLibrary')
}

export async function ensureCameraPermission(): Promise<boolean> {
  const cur = await ImagePicker.getCameraPermissionsAsync()
  if (cur.granted) return true
  if (!cur.canAskAgain) throw new PermissionDeniedError('camera')
  // D.2 Android prominent-disclosure. iOS / already-disclosed paths
  // resolve synchronously without showing UI.
  await disclose('camera')
  const next = await ImagePicker.requestCameraPermissionsAsync()
  if (next.granted) return true
  throw new PermissionDeniedError('camera')
}

/** Routes the user to the system settings page for the current platform. */
export function openSystemSettings(): void {
  if (Platform.OS === 'ios') {
    Linking.openURL('app-settings:').catch(() => Linking.openSettings())
  } else {
    Linking.openSettings()
  }
}
