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

export async function GET() {
  const result = await postgresClient.query(
    `SELECT id, name, webhook_url, enabled, last_notified_at, created_at
     FROM openclaw_instances
     ORDER BY created_at`
  );
  return NextResponse.json({ data: result.rows });
}

export async function POST(request: NextRequest) {
  const body = await request.json();
  const { name, webhook_url, webhook_secret, enabled = true } = body;

  if (!name || !webhook_url || !webhook_secret) {
    return NextResponse.json(
      { error: 'name, webhook_url, and webhook_secret are required' },
      { status: 400 }
    );
  }

  const result = await postgresClient.query(
    `INSERT INTO openclaw_instances (name, webhook_url, webhook_secret, enabled)
     VALUES ($1, $2, $3, $4)
     RETURNING id, name, webhook_url, enabled, created_at`,
    [name, webhook_url, webhook_secret, enabled]
  );

  return NextResponse.json({ data: result.rows[0] }, { status: 201 });
}
