import { getWebhookUrl } from '@/lib/config';

export interface FileUploadResponse {
  success: boolean;
  message: string;
  url?: string;  // The URL from the API response
  fileUrl?: string; // For backward compatibility
  id?: string; // Add other fields as needed based on your API response
}

export const uploadBlogFile = async (file: File, blogId?: string): Promise<FileUploadResponse> => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('blog_id', blogId);

  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const response = await apiFetch(`${getWebhookUrl()}/file_upload_blog`, {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return {
      success: true,
      message: 'File uploaded successfully',
      url: data.url,
      fileUrl: data.url,
      ...data
    };
  } catch (error) {
    console.error('Error uploading file:', error);
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Failed to upload file',
    };
  }
};

export const uploadEventFile = async (file: File, eventId?: string): Promise<FileUploadResponse> => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('event_id', eventId);

  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const response = await apiFetch(`${getWebhookUrl()}/file_upload_event`, {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return {
      success: true,
      message: 'File uploaded successfully',
      url: data.url,
      fileUrl: data.url,
      ...data
    };
  } catch (error) {
    console.error('Error uploading file:', error);
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Failed to upload file',
    };
  }
};

export const uploadTmpFile = async (file: File): Promise<FileUploadResponse> => {
  const formData = new FormData();
  formData.append('file', file);

  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const response = await apiFetch(`${getWebhookUrl()}/upload_tmp`, {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return {
      success: true,
      message: 'File uploaded successfully',
      url: data.url,
      fileUrl: data.url,
      ...data
    };
  } catch (error) {
    console.error('Error uploading file:', error);
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Failed to upload file',
    };
  }
};

export const generateBlogPostImage = async (blogId: string, title: string): Promise<FileUploadResponse> => {
  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const response = await apiFetch(`${getWebhookUrl()}/media/image_generator`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        blog_id: blogId,
        title: title
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return {
      success: true,
      message: 'Blog post image generated successfully',
      url: data.url || data.imageUrl,
      fileUrl: data.url || data.imageUrl,
      ...data
    };
  } catch (error) {
    console.error('Error generating blog post image:', error);
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Failed to generate blog post image',
    };
  }
};

export const generateAIImage = async (prompt: string): Promise<FileUploadResponse> => {
  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const response = await apiFetch(`${getWebhookUrl()}/file_upload`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        prompt,
      }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    return {
      success: true,
      message: 'Image generated successfully',
      fileUrl: data.imageUrl,
      ...data
    };
  } catch (error) {
    console.error('Error generating image:', error);
    return {
      success: false,
      message: error instanceof Error ? error.message : 'Failed to generate image',
    };
  }
};
