/**
 * Admin API — single notify_event_key update and delete.
 * PUT: update display_label, description, sort_order, is_active by key.
 * DELETE: hard delete one event key by primary key.
 */

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

function toRow(row: Record<string, unknown>) {
  return {
    key: row.key,
    displayLabel: row.display_label,
    description: row.description,
    sortOrder: row.sort_order,
    isActive: row.is_active,
    createdAt: row.created_at,
    updatedAt: row.updated_at,
  };
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ key: string }> }
) {
  const { error } = await requireAdmin();
  if (error) return error;

  try {
    const { key } = await params;
    const body = await request.json();
    const { display_label, description, sort_order, is_active } = body;

    const result = await postgresClient.query(
      `UPDATE notify_event_keys
       SET display_label = COALESCE($1, display_label),
           description = COALESCE($2, description),
           sort_order = COALESCE($3, sort_order),
           is_active = COALESCE($4, is_active),
           updated_at = NOW()
       WHERE key = $5
       RETURNING key, display_label, description, sort_order, is_active, created_at, updated_at`,
      [display_label ?? null, description ?? null, sort_order ?? null, is_active ?? null, key]
    );

    if (result.rows.length === 0) {
      return NextResponse.json({ error: 'Event key not found' }, { status: 404 });
    }

    return NextResponse.json({ data: toRow(result.rows[0]) });
  } catch (err) {
    console.error('PUT /api/admin/notify-event-keys/[key] failed:', err);
    return NextResponse.json(
      { error: 'Failed to update event key', message: err instanceof Error ? err.message : 'unknown' },
      { status: 500 }
    );
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ key: string }> }
) {
  const { error } = await requireAdmin();
  if (error) return error;

  try {
    const { key } = await params;

    const result = await postgresClient.query(
      `DELETE FROM notify_event_keys WHERE key = $1 RETURNING key`,
      [key]
    );

    if (result.rows.length === 0) {
      return NextResponse.json({ error: 'Event key not found' }, { status: 404 });
    }

    return NextResponse.json({ deleted: true, key: result.rows[0].key });
  } catch (err) {
    console.error('DELETE /api/admin/notify-event-keys/[key] failed:', err);
    return NextResponse.json(
      { error: 'Failed to delete event key', message: err instanceof Error ? err.message : 'unknown' },
      { status: 500 }
    );
  }
}
