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

/** PUT /api/admin/feeds/[id] — Update feed config */
export const PUT: APIRoute = async ({ params, request }) => {
  try {
    const id = parseInt(params.id!);
    const body = await request.json();
    const fields: string[] = [];
    const values: any[] = [];
    let idx = 1;

    const allowed = ['name', 'merchant_name', 'feed_url', 'sync_frequency', 'is_enabled', 'priority', 'config', 'external_id'];
    for (const key of allowed) {
      if (body[key] !== undefined) {
        fields.push(`${key} = $${idx}`);
        values.push(key === 'config' ? JSON.stringify(body[key]) : body[key]);
        idx++;
      }
    }

    if (fields.length === 0) {
      return new Response(JSON.stringify({ error: 'No fields to update' }), { status: 400 });
    }

    fields.push(`updated_at = NOW()`);
    values.push(id);

    const result = await query(
      `UPDATE feeds SET ${fields.join(', ')} WHERE id = $${idx} RETURNING *`,
      values
    );

    if (result.rowCount === 0) {
      return new Response(JSON.stringify({ error: 'Feed not found' }), { status: 404 });
    }

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

/** DELETE /api/admin/feeds/[id] — Remove feed */
export const DELETE: APIRoute = async ({ params }) => {
  try {
    const id = parseInt(params.id!);

    // Delete offers, sync logs, mappings first
    await query('DELETE FROM product_offers WHERE feed_id = $1', [id]);
    await query('DELETE FROM sync_logs WHERE feed_id = $1', [id]);
    await query('DELETE FROM field_mappings WHERE feed_id = $1', [id]);
    const result = await query('DELETE FROM feeds WHERE id = $1 RETURNING id', [id]);

    if (result.rowCount === 0) {
      return new Response(JSON.stringify({ error: 'Feed not found' }), { status: 404 });
    }

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