import { getDatabase } from '../index';
import { NewsItem } from '../../../types';
import { generateUUID } from '../../utils/uuid';
import { now } from '../../utils/datetime';

export async function cacheNewsItems(items: NewsItem[]): Promise<void> {
  const db = getDatabase();
  const timestamp = now();

  for (const item of items) {
    // Upsert news item
    await db.runAsync(
      `INSERT OR REPLACE INTO news_items (id, title, excerpt, url, content_html, published_at, cached_at)
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [
        item.id,
        item.title,
        item.excerpt || null,
        item.url || null,
        item.contentHtml || null,
        item.publishedAt,
        timestamp,
      ]
    );
  }
}

export async function getCachedNewsItems(limit: number = 20): Promise<NewsItem[]> {
  const db = getDatabase();
  const rows = await db.getAllAsync<any>(
    'SELECT * FROM news_items ORDER BY published_at DESC LIMIT ?',
    [limit]
  );

  return rows.map(row => ({
    id: row.id,
    title: row.title,
    excerpt: row.excerpt || undefined,
    url: row.url || undefined,
    contentHtml: row.content_html || undefined,
    publishedAt: row.published_at,
  }));
}

export async function clearOldNewsCache(daysToKeep: number = 30): Promise<void> {
  const db = getDatabase();
  const cutoffDate = new Date();
  cutoffDate.setDate(cutoffDate.getDate() - daysToKeep);

  await db.runAsync(
    'DELETE FROM news_items WHERE cached_at < ?',
    [cutoffDate.toISOString()]
  );
}
