import { NextRequest, NextResponse } from 'next/server';
import { getITGlueSyncService } from '@/lib/services/itglue-sync-service';
import postgresClient from '@/lib/services/postgres-client';

export async function POST(req: NextRequest) {
  const body = await req.json().catch(() => ({}));
  const triggeredBy = body.triggeredBy || 'manual';

  const svc = getITGlueSyncService();
  if (svc.isSyncInProgress()) {
    return NextResponse.json({ error: 'Sync already in progress' }, { status: 409 });
  }

  // Fire and forget — return immediately, sync runs in background
  svc.fullSync(triggeredBy).catch(err =>
    console.error('[ITGlue] Background sync error:', err.message)
  );

  return NextResponse.json({ ok: true, message: 'IT Glue sync started' });
}

export async function GET() {
  try {
    const svc = getITGlueSyncService();
    const inProgress = svc.isSyncInProgress();

    const { rows } = await postgresClient.query(
      `SELECT id, sync_type, status, triggered_by, started_at, completed_at,
              duration_ms, total_upserted, entities, error
       FROM itg_sync_history
       ORDER BY started_at DESC
       LIMIT 10`
    );

    const counts = await postgresClient.query(`
      SELECT
        (SELECT COUNT(*) FROM itg_organizations)       AS organizations,
        (SELECT COUNT(*) FROM itg_configurations)      AS configurations,
        (SELECT COUNT(*) FROM itg_flexible_assets)     AS flexible_assets,
        (SELECT COUNT(*) FROM itg_contacts)            AS contacts,
        (SELECT COUNT(*) FROM itg_passwords)           AS passwords,
        (SELECT COUNT(*) FROM itg_documents)           AS documents,
        (SELECT COUNT(*) FROM itg_locations)           AS locations,
        (SELECT COUNT(*) FROM itg_domains)             AS domains
    `);

    return NextResponse.json({
      inProgress,
      counts: counts.rows[0],
      history: rows,
    });
  } catch (err: any) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}
