#!/bin/sh
set -e

echo "Running Prisma migrations..."
node ./node_modules/prisma/build/index.js migrate deploy

# Background scheduler: call /api/cron/agents every 5 minutes
(
  sleep 60
  while true; do
    node -e "
      const http = require('http');
      const req = http.request('http://localhost:3000/api/cron/agents', { method: 'POST' }, (res) => {
        let body = '';
        res.on('data', (d) => body += d);
        res.on('end', () => console.log('[Scheduler] Cron response:', res.statusCode, body));
      });
      req.on('error', (e) => console.error('[Scheduler] Cron error:', e.message));
      req.end();
    " 2>&1 || true
    sleep 300
  done
) &

echo "Starting server..."
exec node server.js
