export const dynamic = 'force-dynamic';
export const revalidate = 0;

import { NextResponse } from 'next/server';
import { getSql } from '../../../lib/db.js';
import { runMemoryMaintenance } from '../../../lib/maintenance.js';
import { logActivity } from '../../../lib/audit.js';
import { timingSafeCompare } from '../../../lib/timing-safe.js';

// GET /api/cron/memory-maintenance - Vercel Cron handler
export async function GET(request) {
  try {
    // SECURITY: Always require CRON_SECRET
    const cronSecret = process.env.CRON_SECRET;
    if (!cronSecret) {
      return NextResponse.json({ error: 'CRON_SECRET not configured' }, { status: 503 });
    }
    const authHeader = request.headers.get('authorization');
    if (!authHeader || !timingSafeCompare(authHeader, `Bearer ${cronSecret}`)) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const sql = getSql();
    const summary = { orgs_processed: 0, agents_notified: 0, messages_sent: 0 };

    // Load active orgs
    const orgs = await sql`
      SELECT id, name FROM organizations WHERE id != 'org_default'
    `;

    for (const org of orgs) {
      try {
        const result = await runMemoryMaintenance(org.id, sql);
        
        if (result.status === 'processed') {
          summary.agents_notified += result.agents_notified;
          summary.messages_sent += result.messages_sent;

          logActivity({
            orgId: org.id, actorId: 'cron', actorType: 'cron',
            action: 'memory.maintenance_run', resourceType: 'agent',
            details: { notified: result.agents_notified, messages: result.messages_sent },
          }, sql);
        }

        summary.orgs_processed++;
      } catch (err) {
        console.error(`[CRON-MAINTENANCE] Error processing org ${org.id}:`, err.message);
        summary.orgs_processed++;
      }
    }

    return NextResponse.json({ success: true, summary });
  } catch (error) {
    console.error('Cron memory maintenance error:', error);
    return NextResponse.json({ error: 'Maintenance job failed' }, { status: 500 });
  }
}
