import { useQuery } from '@tanstack/react-query';
import {
  createAudioFile,
  deleteAudioFile,
  listAudioFiles,
} from '@/shared/api/audioFiles';
import { getApiListRows } from '@/shared/business/apiListRows';
import { useInvalidatingMutation } from '@/shared/business/queryMutations';
import {
  generateSoundRecipe,
  generateSoundTitle,
} from '@/business/audio-files/generate';

export const AUDIO_FILES_QUERY_KEY = ['audio-files'] as const;

/**
 * The audio library visible to the caller: global defaults + own campus rows
 * (`READ_AUDIO_FILES`). `retry: false` so a caller without the permission (e.g.
 * a non-campus role opening the timer) silently falls back to the built-ins
 * instead of retrying a 403.
 */
export function useAudioFiles() {
  return useQuery({
    queryKey: AUDIO_FILES_QUERY_KEY,
    queryFn: () => getApiListRows(listAudioFiles()),
    retry: false,
  });
}

/**
 * Generate a new synthesized sound and persist it as a `recipe` row. An optional
 * user-supplied `name` becomes the title; a generated name is the fallback.
 */
export function useGenerateAudioFile() {
  return useInvalidatingMutation({
    mutationFn: (name?: string) =>
      createAudioFile({
        kind: 'recipe',
        title: name && name.trim() ? name.trim() : generateSoundTitle(),
        recipe: generateSoundRecipe(),
      }),
    invalidateQueryKey: AUDIO_FILES_QUERY_KEY,
  });
}

export function useDeleteAudioFile() {
  return useInvalidatingMutation({
    mutationFn: (id: string) => deleteAudioFile(id),
    invalidateQueryKey: AUDIO_FILES_QUERY_KEY,
  });
}
