/* eslint-disable @typescript-eslint/no-explicit-any */

export function removeFalsyValues<T extends Record<string, any>>(
  obj: T,
  excludeKeys: (keyof T)[] = []
): Partial<T> {
  return Object.entries(obj).reduce((acc, [key, value]) => {
    if (value || excludeKeys.includes(key as keyof T)) {
      acc[key as keyof T] = value;
    }
    return acc;
  }, {} as Partial<T>);
}

export function delay(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export async function imageUrlToBase64(url: string): Promise<string> {
  const response = await fetch(url);
  const blob = await response.blob();

  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onloadend = () => {
      if (typeof reader.result === "string") {
        // Kết quả là data URL (base64)
        resolve(reader.result.split(",")[1]);
      } else {
        reject("Không thể đọc dữ liệu ảnh");
      }
    };
    reader.onerror = reject;
    reader.readAsDataURL(blob);
  });
}

export function isBlobUrl(url: string): boolean {
  return url.startsWith("blob:");
}
