/**
 * QBO Disconnect
 * GET /api/qbo/disconnect — revokes QBO token and removes from DB
 */

import { NextResponse } from 'next/server';
import postgresClient from '@/lib/services/postgres-client';

export async function GET() {
  const realmId = process.env.QBO_REALM_ID || '';
  const baseUrl = process.env.NEXTAUTH_URL || 'https://pulse.wulfconsulting.cloud';

  try {
    await postgresClient.query(`DELETE FROM qbo_tokens WHERE realm_id = $1`, [realmId]);
    console.log(`[QBO] Disconnected realm ${realmId}`);
    return NextResponse.redirect(`${baseUrl}/admin/qbo?disconnected=true`);
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    return NextResponse.redirect(`${baseUrl}/admin/qbo?error=${encodeURIComponent(msg)}`);
  }
}
