export interface Article {
  id: number;
  newspaper: string;
  edition: string;
  page: number;
  date: string;
  headline: string;
  subheadline: string;
  category: string;
  subcategory: string;
  language: string;
  author: string;
  text: string;
  summary: string;
  keywords: string[];
  persons: string[];
  locations: string[];
  organizations: string[];
  sentiment: string;
  image_path: string;
  confidence: number;
}

export interface UploadJob {
  id: number;
  filename: string;
  newspaper: string;
  edition: string;
  date: string;
  status: string;
  error_message?: string;
  created_time: string;
}

export async function searchArticles(query: string, isSemantic: boolean, jobId?: number): Promise<Article[]> {
  const url = new URL('/api/search', window.location.origin);
  if (query) url.searchParams.append('q', query);
  if (jobId) url.searchParams.append('job_id', jobId.toString());
  if (isSemantic) url.searchParams.append('semantic', 'true');
  
  const response = await fetch(url.toString(), {
    method: 'GET',
    headers: {
      'Accept': 'application/json',
    },
    // Prevent Next.js from caching dynamic search results
    cache: 'no-store' 
  });
  
  if (!response.ok) {
    throw new Error('Failed to fetch articles');
  }
  
  return response.json();
}

export async function uploadPDF(file: File, newspaper: string, edition: string, date: string) {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('newspaper', newspaper);
  formData.append('edition', edition);
  formData.append('date', date);

  const response = await fetch('/api/upload', {
    method: 'POST',
    body: formData,
  });

  if (!response.ok) {
    throw new Error('Failed to upload PDF');
  }

  return response.json();
}

export async function getJobs(): Promise<UploadJob[]> {
  const response = await fetch('/api/jobs', {
    method: 'GET',
    cache: 'no-store'
  });
  if (!response.ok) {
    throw new Error('Failed to fetch jobs');
  }
  return response.json();
}

export async function updateArticle(id: number, updates: Partial<Article>): Promise<Article> {
  const response = await fetch(`/api/articles/${id}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(updates),
  });
  if (!response.ok) {
    throw new Error('Failed to update article');
  }
  return response.json();
}
