import { ref } from 'vue';
import axios from 'axios';
import { useFileBlobCache } from './useFileBlobCache';

/**
 * Composable for fetching and managing a list of photos for a specific entity.
 */
export function usePhotoList() {
    const { getFile, preCacheFiles, blobCache } = useFileBlobCache();
    
    const photos = ref([]);
    const loading = ref(false);
    const error = ref(null);

    /**
     * Fetch photos for a target hash and type.
     * 
     * @param {string} targetHash 
     * @param {string} type - 'StoreMarket', 'ProductMarket', 'User'
     */
    const fetchPhotos = async (targetHash, type = 'StoreMarket') => {
        if (!targetHash) return;
        
        loading.value = true;
        error.value = null;

        try {
            const response = await axios.post(`/Request/Photos/${type}`, {
                target: targetHash
            });

            if (response.data && Array.isArray(response.data)) {
                photos.value = response.data;
                // Pre-cache all blobs for these hashes
                await preCacheFiles(photos.value);
            } else {
                photos.value = [];
            }
        } catch (err) {
            console.error('Error fetching photos:', err);
            error.value = 'Failed to load photos.';
            photos.value = [];
        } finally {
            loading.value = false;
        }
    };

    return {
        photos,
        loading,
        error,
        fetchPhotos,
        blobCache,
        getFile
    };
}
