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

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const body = await request.json();
  const { name, webhook_url, webhook_secret, enabled } = body;

  const sets: string[] = [];
  const values: unknown[] = [];

  if (name !== undefined) { values.push(name); sets.push(`name = $${values.length}`); }
  if (webhook_url !== undefined) { values.push(webhook_url); sets.push(`webhook_url = $${values.length}`); }
  if (webhook_secret !== undefined) { values.push(webhook_secret); sets.push(`webhook_secret = $${values.length}`); }
  if (enabled !== undefined) { values.push(enabled); sets.push(`enabled = $${values.length}`); }

  if (sets.length === 0) {
    return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
  }

  values.push(id);
  const result = await postgresClient.query(
    `UPDATE openclaw_instances SET ${sets.join(', ')}
     WHERE id = $${values.length}
     RETURNING id, name, webhook_url, enabled, last_notified_at, created_at`,
    values
  );

  if (result.rowCount === 0) {
    return NextResponse.json({ error: 'Not found' }, { status: 404 });
  }

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

export async function DELETE(
  _request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  const result = await postgresClient.query(
    `DELETE FROM openclaw_instances WHERE id = $1 RETURNING id`,
    [id]
  );

  if (result.rowCount === 0) {
    return NextResponse.json({ error: 'Not found' }, { status: 404 });
  }

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