// Create a new blog entry and return its id
export const newBlog = async (): Promise<string | null> => {
  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const { getWebhookUrl } = await import('@/lib/config');
    const response = await apiFetch(`${getWebhookUrl()}/blog/new_blog`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      // ggf. weitere Daten je nach API, aktuell leer
    });
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    // Annahme: neue id ist in data.id oder data.blog_id
    return data.id || data.blog_id || null;
  } catch (error) {
    console.error('Error creating new blog:', error);
    return null;
  }
};

// Generate a blog post via backend
export interface PublishBlogPostParams {
  blogId: string;
  publishDate?: string;
  publishToSocialMedia: boolean;
  socialMediaChannels: string[];
  socialMediaLanguages: string[];
}

export const publishBlogPost = async ({
  blogId,
  publishDate,
  publishToSocialMedia,
  socialMediaChannels,
  socialMediaLanguages
}: PublishBlogPostParams): Promise<any> => {
  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const { getWebhookUrl } = await import('@/lib/config');
    const response = await apiFetch(`${getWebhookUrl()}/blog/publish`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        blog_id: blogId,
        publish_date: publishDate || new Date().toISOString().split('T')[0],
        publish_socialmedia: publishToSocialMedia,
        socialmedia_channels: socialMediaChannels,
        socialmedia_languages: socialMediaLanguages
      })
    });

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

    return await response.json();
  } catch (error) {
    console.error('Error publishing blog post:', error);
    throw error;
  }
};

export const updateBlogPost = async ({
  blogId,
  content,
}: {
  blogId: string;
  content: any;
}): Promise<any> => {
  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const { getWebhookUrl } = await import('@/lib/config');
    const response = await apiFetch(`${getWebhookUrl()}/blog/update`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ 
        blog_id: blogId,
        content 
      })
    });

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

    return await response.json();
  } catch (error) {
    console.error('Error updating blog post:', error);
    throw error;
  }
};

export const generateBlogPost = async ({
  blog_Id,
  topic,
  tonality,
  languages,
}: {
  blog_Id: string;
  topic: string;
  tonality: string;
  languages: string[];
}): Promise<any> => {
  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const { getWebhookUrl } = await import('@/lib/config');
    const response = await apiFetch(`${getWebhookUrl()}/blog/generate`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        blog_Id,
        topic,
        tonality,
        languages,
      }),
    });
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return await response.json();
  } catch (error) {
    console.error('Error generating blog post:', error);
    throw error;
  }
};

// Fetch blog topic suggestions from backend
export const fetchBlogTopicSuggestions = async (): Promise<string[] | null> => {
  try {
    const { apiFetch } = await import('@/utils/apiFetch');
    const { getWebhookUrl } = await import('@/lib/config');
    const response = await apiFetch(`${getWebhookUrl()}/blog/topic_suggestion`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      }
    });
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const res = await response.json();
    const arr = res?.topics || res;
    if (Array.isArray(arr)) return arr.slice(0, 4);
    return null;
  } catch (error) {
    console.error('Error fetching blog topic suggestions:', error);
    return null;
  }
};
