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

const CRON_DEFINITIONS = [
  { name: 'nightly-sync', schedule: '0 2 * * *', description: 'Feed synchronization' },
  { name: 'process-cutouts', schedule: '30 3 * * *', description: 'Process product cutout images' },
  { name: 'check-price-alerts', schedule: '0 8 * * *', description: 'Check and send price alerts' },
  { name: 'aggregate-stats', schedule: '0 1 * * *', description: 'Aggregate daily statistics' },
  { name: 'update-homepage', schedule: '0 6 * * *', description: 'Auto-update homepage sections' },
  { name: 'update-deals', schedule: '15 6 * * *', description: 'Auto-update deals from price drops' },
  { name: 'send-watchlist-digest', schedule: '0 9 * * 1', description: 'Weekly watchlist digest email' },
];

export const GET: APIRoute = async () => {
  try {
    const lastRuns = await query(`
      SELECT DISTINCT ON (name) name, started_at, finished_at, status, output_summary, error_message,
        EXTRACT(EPOCH FROM (finished_at - started_at)) as duration_secs
      FROM cron_runs ORDER BY name, started_at DESC
    `);

    const runMap = new Map(lastRuns.rows.map((r: any) => [r.name, r]));
    const crons = CRON_DEFINITIONS.map(def => ({
      ...def,
      last_run: runMap.get(def.name) || null,
    }));

    return Response.json({ crons });
  } catch (err: any) {
    return Response.json({ error: err.message || 'Query failed' }, { status: 500 });
  }
};

export const POST: APIRoute = async ({ request }) => {
  try {
    const { name } = await request.json();
    const def = CRON_DEFINITIONS.find(d => d.name === name);
    if (!def) return Response.json({ error: 'Unknown cron' }, { status: 400 });

    // Log the manual trigger
    await query(`INSERT INTO cron_runs (name, status, output_summary) VALUES ($1, 'triggered', 'Manual trigger from admin')`, [name]);

    return Response.json({ ok: true, message: `Triggered ${name}` });
  } catch (err: any) {
    return Response.json({ error: err.message || 'Trigger failed' }, { status: 500 });
  }
};
