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

export async function POST(req: NextRequest) {
  const disabledRes = await postgresClient.query<{ disabled: boolean }>(
    `SELECT disabled FROM integration_settings WHERE key = 'pax8'`
  );
  if (disabledRes.rows[0]?.disabled === true) {
    return NextResponse.json(
      { error: 'PAX8 is disabled', message: 'PAX8 sync is disabled via /admin/integrations' },
      { status: 403 }
    );
  }

  const body = await req.json().catch(() => ({}));
  const triggeredBy = body.triggeredBy || 'manual';

  const svc = getPax8SyncService();
  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('[Pax8Sync] Background sync error:', err.message)
  );

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

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

    const counts = await postgresClient.query(`
      SELECT
        (SELECT COUNT(*) FROM pax8_companies     WHERE is_deleted = false) AS companies,
        (SELECT COUNT(*) FROM pax8_subscriptions WHERE is_deleted = false) AS subscriptions,
        (SELECT COUNT(*) FROM pax8_products      WHERE is_deleted = false) AS products
    `);

    const history = await postgresClient.query(
      `SELECT id, sync_type, status, started_at, completed_at,
              records_added, records_updated, records_deleted, error_message, triggered_by
       FROM sync_history
       WHERE entity_type = 'pax8'
       ORDER BY started_at DESC
       LIMIT 10`
    );

    return NextResponse.json({
      inProgress,
      counts: counts.rows[0],
      history: history.rows,
    });
  } catch (err) {
    return NextResponse.json(
      { error: err instanceof Error ? err.message : 'Failed to get PAX8 sync status' },
      { status: 500 }
    );
  }
}
