'use client'

export default function openinaryLoader({ src, width, quality }: { src: string, width: number, quality?: number }) {
    // Handle already absolute openinary URLs
    let path = src;
    if (src.startsWith('https://media.ayris.tech/t/')) {
        // format: https://media.ayris.tech/t/w_800,h_800/moyqr/img.jpg
        const parts = src.split('/');
        path = parts.slice(5).join('/');
    } else if (src.startsWith('https://media.ayris.tech/upload/')) {
        // format: https://media.ayris.tech/upload/moyqr/img.jpg
        const parts = src.split('/');
        path = parts.slice(4).join('/');
    } else if (src.includes('res.cloudinary.com')) {
        // Correctly apply width & quality for unmigrated Cloudinary URLs
        // e.g. https://res.cloudinary.com/domain/image/upload/v1234/path.jpg
        // becomes: https://res.cloudinary.com/domain/image/upload/w_800,f_webp,q_75/v1234/path.jpg
        const parts = src.split('/upload/');
        if (parts.length === 2) {
            return `${parts[0]}/upload/w_${width},f_webp,q_${quality || 75}/${parts[1]}`;
        }
        return src;
    } else if (src.startsWith('http')) {
        // For other external URLs, we append the width as a query parameter to satisfy Next.js.
        const url = new URL(src);
        url.searchParams.set('w', width.toString());
        if (quality) {
            url.searchParams.set('q', quality.toString());
        }
        return url.toString();
    }

    // Clean up any leading slash
    if (path.startsWith('/')) {
        path = path.substring(1);
    }

    // Ensure 'starapart/' prefix for Openinary transform URLs
    // Since the API sometimes returns URLs without the root folder, we inject it back.
    if (!path.startsWith('starapart/') && !path.startsWith('http')) {
        path = `starapart/${path}`;
    }

    // Adding a_auto to automatically rotate images based on EXIF data (fixes sideways phone photos)
    return `https://media.ayris.tech/t/w_${width},f_webp,q_${quality || 75},a_auto/${path}`
}
