/**
 * Upload image/file using centralized API flow
 */

import { uploadImage as uploadImageApi } from "./api/apis";

interface UploadOptions {
  maxSizeMB?: number; // Default 2.5MB
  allowedTypes?: string[]; // Default: JPG, JPEG, PNG
}

export async function uploadImageToBackend(
  file: File,
  options?: UploadOptions
): Promise<string> {
  // Set defaults
  const maxSizeMB = options?.maxSizeMB || 2.5;
  const allowedTypes = options?.allowedTypes || ["image/jpeg", "image/png"];

  // Validate file type
  if (!allowedTypes.includes(file.type)) {
    throw new Error(
      `Only ${allowedTypes.join(", ")} files are allowed.`
    );
  }

  // Validate file size
  const maxSize = maxSizeMB * 1024 * 1024;
  if (file.size > maxSize) {
    throw new Error(`Please upload file under ${maxSizeMB}MB`);
  }

  try {
    const response = await uploadImageApi(file);

    if (!response.status) {
      throw new Error(response.message || "Failed to upload file");
    }

    // Handle different response formats
    const fileUrl = (response.data as any)?.file_url;

    if (!fileUrl) {
      throw new Error("No file URL returned from server");
    }

    return fileUrl;
  } catch (error: any) {
    console.error("File upload error:", error);
    throw new Error(error?.message || "Failed to upload file");
  }
}
