import { NextRequest, NextResponse } from 'next/server';
import { isZoomConfigured } from '@/lib/services/zoom-factory';
import { getZoomSyncService } from '@/lib/services/zoom-sync-service';
import { postgresClient } from '@/lib/services/postgres-client';

export async function POST(_request: NextRequest) {
  if (!isZoomConfigured()) {
    return NextResponse.json(
      { error: 'Zoom credentials not configured' },
      { status: 503 }
    );
  }

  const service = getZoomSyncService();

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

  // Fire-and-forget
  service.sync().catch(err => {
    console.error('[ZOOM-SYNC] Background sync failed:', err);
  });

  return NextResponse.json({ started: true });
}

export async function GET(_request: NextRequest) {
  const service = getZoomSyncService();

  let lastSynced: Date | null = null;
  try {
    const result = await postgresClient.query(
      `SELECT MAX(synced_at) as last_synced FROM zoom_users`
    );
    lastSynced = result.rows[0]?.last_synced ?? null;
  } catch {
    // Table may not exist yet
  }

  return NextResponse.json({
    isSyncing: service.isSyncInProgress(),
    lastSynced,
    configured: isZoomConfigured(),
  });
}
