import { readConfig } from '../config/store';
import { flushQueue } from '../queue/flush';
import { pendingCount } from '../storage/queue';

export async function sync(background: boolean): Promise<void> {
  const config = readConfig();

  if (!config || !config.enabled) {
    return;
  }

  // Drain in rounds since flushQueue only processes a bounded batch per call.
  let delivered = 0;
  let authInvalid = false;

  for (let i = 0; i < 20 && pendingCount() > 0; i++) {
    const result = await flushQueue(config);
    delivered += result.delivered;
    authInvalid = authInvalid || result.authInvalid;

    if (result.delivered === 0) {
      break;
    }
  }

  if (background) {
    return;
  }

  console.log(`Delivered ${delivered} prompt(s). ${pendingCount()} still pending.`);

  if (authInvalid) {
    console.error('Device token was rejected by the API. Run `prompt-agent login` again.');
    process.exitCode = 1;
  }
}
