import type { APIRoute } from 'astro';
import { query } from '../../../../../lib/feeds/db.js';

/** GET /api/admin/feeds/[id]/logs — Sync history */
export const GET: APIRoute = async ({ params, url }) => {
  try {
    const id = parseInt(params.id!);
    const limit = parseInt(url.searchParams.get('limit') || '20');
    const offset = parseInt(url.searchParams.get('offset') || '0');

    const result = await query(
      `SELECT * FROM sync_logs
       WHERE feed_id = $1
       ORDER BY started_at DESC
       LIMIT $2 OFFSET $3`,
      [id, limit, offset]
    );

    const countResult = await query(
      'SELECT COUNT(*) as total FROM sync_logs WHERE feed_id = $1',
      [id]
    );

    return new Response(JSON.stringify({
      logs: result.rows,
      total: parseInt(countResult.rows[0].total),
    }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (err: any) {
    return new Response(JSON.stringify({ error: err.message }), { status: 500 });
  }
};
