/**
 * PWA Caches Query Hooks
 *
 * React Query hooks for fetching PWA cache data.
 */

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

interface PwaCache {
  id: string;
  projectId: string;
  asset_url: string;
  asset_type: string;
  size_bytes: number;
  cached_at: string;
  expires_at: string | null;
}

interface PwaCacheListResponse {
  rows: PwaCache[];
  count: number;
}

/**
 * Fetch list of PWA caches for a project
 */
export function usePwaCachesQuery(projectId: string | undefined) {
  return useQuery({
    queryKey: queryKeys.pwaCaches.list(projectId || ''),
    queryFn: async (): Promise<PwaCache[]> => {
      const response = await axios.get<PwaCacheListResponse>(
        `pwa_caches?projectId=${projectId}`,
      );
      return response.data.rows;
    },
    enabled: !!projectId,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Delete PWA cache entry mutation
 */
export function useDeletePwaCacheMutation() {
  const queryClient = useQueryClient();

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

export default usePwaCachesQuery;
