import { NextRequest, NextResponse } from 'next/server';
import { runMimecastFullSync, runMimecastIncrementalSync, getMimecastStats } from '@/lib/services/mimecast-sync-service';

let _syncing = false;

export async function POST(req: NextRequest) {
  if (_syncing) {
    return NextResponse.json({ error: 'Sync already in progress' }, { status: 409 });
  }

  try {
    const body = await req.json().catch(() => ({}));
    const syncType = body.syncType ?? 'incremental';

    _syncing = true;

    const result = syncType === 'full'
      ? await runMimecastFullSync()
      : await runMimecastIncrementalSync();

    return NextResponse.json({
      success: true,
      syncType,
      ...result,
    });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  } finally {
    _syncing = false;
  }
}

export async function GET() {
  try {
    const stats = await getMimecastStats();
    return NextResponse.json({ isSyncing: _syncing, ...stats });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
