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

/** GET /api/admin/feeds — List all feeds with status */
export const GET: APIRoute = async () => {
  try {
    const result = await query(
      `SELECT f.*, p.slug as provider_slug, p.name as provider_name
       FROM feeds f
       JOIN providers p ON f.provider_id = p.id
       ORDER BY f.created_at DESC`
    );

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

/** POST /api/admin/feeds — Add new feed */
export const POST: APIRoute = async ({ request }) => {
  try {
    const body = await request.json();
    const { provider_id, external_id, name, merchant_name, feed_url, sync_frequency, priority, config } = body;

    if (!provider_id || !name) {
      return new Response(JSON.stringify({ error: 'provider_id and name are required' }), { status: 400 });
    }

    const result = await query(
      `INSERT INTO feeds (provider_id, external_id, name, merchant_name, feed_url, sync_frequency, priority, config)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
       RETURNING *`,
      [
        provider_id,
        external_id || null,
        name,
        merchant_name || null,
        feed_url || null,
        sync_frequency || '4h',
        priority || 0,
        JSON.stringify(config || {}),
      ]
    );

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