import { fetchAPI } from '../services/api';

/**
 * Optimizer API Client
 * Functions for content optimization operations
 */

export type EntryPoint = 'auto' | 'writer' | 'wordpress' | 'external' | 'manual';

export interface OptimizationResult {
  content_id: number;
  optimizer_version: number;
  scores_before: {
    seo_score: number;
    readability_score: number;
    engagement_score: number;
    overall_score: number;
  };
  scores_after: {
    seo_score: number;
    readability_score: number;
    engagement_score: number;
    overall_score: number;
  };
  task_id: number | null;
  success: boolean;
}

export interface AnalysisScores {
  seo_score: number;
  readability_score: number;
  engagement_score: number;
  overall_score: number;
  word_count: number;
  has_meta_title: boolean;
  has_meta_description: boolean;
  has_primary_keyword: boolean;
  internal_links_count: number;
}

export const optimizerApi = {
  /**
   * Optimize content (auto-detects entry point based on source)
   * @param contentId - Content ID to optimize
   * @param entryPoint - Optional entry point override (default: 'auto')
   * @returns Optimization result with scores
   */
  optimize: async (contentId: number, entryPoint: EntryPoint = 'auto'): Promise<OptimizationResult> => {
    return await fetchAPI('/v1/optimizer/optimize/', {
      method: 'POST',
      body: JSON.stringify({
        content_id: contentId,
        entry_point: entryPoint,
      }),
    });
  },

  /**
   * Batch optimize multiple content items
   * @param contentIds - Array of content IDs to optimize
   * @param entryPoint - Optional entry point override (default: 'auto')
   * @returns Batch optimization results
   */
  batchOptimize: async (contentIds: number[], entryPoint: EntryPoint = 'auto') => {
    return await fetchAPI('/v1/optimizer/batch_optimize/', {
      method: 'POST',
      body: JSON.stringify({
        content_ids: contentIds,
        entry_point: entryPoint,
      }),
    });
  },

  /**
   * Analyze content without optimizing (preview scores)
   * @param contentId - Content ID to analyze
   * @returns Analysis scores
   */
  analyze: async (contentId: number): Promise<{ content_id: number; scores: AnalysisScores }> => {
    return await fetchAPI('/v1/optimizer/analyze/', {
      method: 'POST',
      body: JSON.stringify({ content_id: contentId }),
    });
  },
};

