export type AssetUrlOptions = {
    baseUrl?: string;
    preferLocal?: boolean;
};

function normalizeAssetPath(path: string): string {
    return path.replace(/^\/+/, '');
}

function joinUrl(baseUrl: string, path: string): string {
    return `${baseUrl.replace(/\/+$/, '')}/${normalizeAssetPath(path)}`;
}

function isExternalUrl(path: string): boolean {
    return /^(https?:)?\/\//i.test(path) || /^(data|blob):/i.test(path);
}

function localAssetUrl(path: string): string {
    const normalizedPath = normalizeAssetPath(path);

    if (import.meta.env.DEV) {
        return `/src/assets/images/${normalizedPath}`;
    }

    return `${import.meta.env.BASE_URL}assets/images/${normalizedPath}`;
}

export function assetUrl(path: string, options: AssetUrlOptions = {}): string {
    if (isExternalUrl(path)) {
        return path;
    }

    const normalizedPath = normalizeAssetPath(path);
    const preferLocal = options.preferLocal ?? (
        import.meta.env.DEV && import.meta.env.VITE_ASSET_DEV_LOCAL !== 'false'
    );

    if (preferLocal) {
        return localAssetUrl(normalizedPath);
    }

    const baseUrl = options.baseUrl ?? import.meta.env.VITE_ASSET_BASE_URL;

    if (baseUrl) {
        return joinUrl(baseUrl, normalizedPath);
    }

    return localAssetUrl(normalizedPath);
}

export function cssAssetUrl(path: string, options?: AssetUrlOptions): string {
    return `url("${assetUrl(path, options).replace(/"/g, '\\"')}")`;
}
