/**
 * Project Audio Tracks Query Hooks
 *
 * React Query hooks for fetching project audio track data.
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';
import { queryKeys } from '../../lib/queryClient';

interface ProjectAudioTrack {
  id: string;
  projectId: string;
  name: string;
  cdn_url: string;
  storage_key: string;
  duration_sec: number;
  environment: 'dev' | 'stage' | 'production';
  order_index: number;
}

interface ProjectAudioTrackListResponse {
  rows: ProjectAudioTrack[];
  count: number;
}

/**
 * Fetch list of audio tracks for a project
 */
export function useProjectAudioTracksQuery(projectId: string | undefined) {
  return useQuery({
    queryKey: queryKeys.projectAudioTracks.list(projectId || ''),
    queryFn: async (): Promise<ProjectAudioTrack[]> => {
      const response = await axios.get<ProjectAudioTrackListResponse>(
        `project_audio_tracks?projectId=${projectId}`,
      );
      return response.data.rows;
    },
    enabled: !!projectId,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Fetch single audio track by ID
 */
export function useProjectAudioTrackQuery(trackId: string | undefined) {
  return useQuery({
    queryKey: queryKeys.projectAudioTracks.detail(trackId || ''),
    queryFn: async (): Promise<ProjectAudioTrack> => {
      const response = await axios.get<ProjectAudioTrack>(
        `project_audio_tracks/${trackId}`,
      );
      return response.data;
    },
    enabled: !!trackId,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Create project audio track mutation
 */
export function useCreateProjectAudioTrackMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (
      data: Partial<ProjectAudioTrack>,
    ): Promise<ProjectAudioTrack> => {
      const response = await axios.post<ProjectAudioTrack>(
        'project_audio_tracks',
        { data },
      );
      return response.data;
    },
    onSuccess: (_, variables) => {
      queryClient.invalidateQueries({
        queryKey: queryKeys.projectAudioTracks.list(variables.projectId || ''),
      });
    },
  });
}

/**
 * Delete project audio track mutation
 */
export function useDeleteProjectAudioTrackMutation() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async ({
      id,
      projectId,
    }: {
      id: string;
      projectId: string;
    }): Promise<void> => {
      await axios.delete(`project_audio_tracks/${id}`);
    },
    onSuccess: (_, { projectId }) => {
      queryClient.invalidateQueries({
        queryKey: queryKeys.projectAudioTracks.list(projectId),
      });
    },
  });
}

export default useProjectAudioTracksQuery;
