import { NextRequest, NextResponse } from 'next/server';
import { validateOpenClawKey } from '@/lib/utils/openclaw-auth';
import { QboSyncService } from '@/lib/services/qbo-sync-service';
import { QboClient } from '@/lib/services/qbo-client';

export async function POST(request: NextRequest) {
  const authError = validateOpenClawKey(request);
  if (authError) return authError;

  try {
    const body = await request.json().catch(() => ({}));
    const syncType: 'full' | 'incremental' = body.syncType === 'incremental' ? 'incremental' : 'full';

    const client = new QboClient();
    const service = new QboSyncService(client);

    if (service.isSyncInProgress()) {
      return NextResponse.json({ error: 'QBO sync already in progress' }, { status: 409 });
    }

    (syncType === 'full'
      ? service.fullSync('openclaw')
      : service.incrementalSync('openclaw')
    ).catch((err) => console.error('[OpenClaw] QBO sync failed:', err));

    return NextResponse.json({
      message: `QBO ${syncType} sync started`,
      syncType,
      triggeredBy: 'openclaw',
    });
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
