/**
 * GET /api/admin/rmm/settings
 *   Returns the cached Overshell config + recent execution counts.
 *
 * PATCH /api/admin/rmm/settings
 *   Body: { overshellVariableName: string }
 *   Updates the variable name the Overshell component expects.
 */

import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { requirePermission } from '@/lib/auth-utils';
import {
  getRmmSettings,
  updateOvershellVariableName,
} from '@/lib/services/rmm/settings';
import postgresClient from '@/lib/services/postgres-client';

const PatchBody = z.object({
  overshellVariableName: z.string().min(1).max(100),
});

interface CountsRow {
  total: string;
  running: string;
  failed_24h: string;
}

export async function GET(_request: NextRequest) {
  const { error } = await requirePermission('admin', 'access');
  if (error) return error;
  const settings = await getRmmSettings();
  const counts = await postgresClient.query<CountsRow>(
    `SELECT
       (SELECT COUNT(*)::text FROM rmm_executions)                                         AS total,
       (SELECT COUNT(*)::text FROM rmm_executions WHERE status = 'running')                AS running,
       (SELECT COUNT(*)::text FROM rmm_executions
         WHERE status = 'failed' AND queued_at >= NOW() - INTERVAL '24 hours')             AS failed_24h`
  );
  return NextResponse.json({
    settings,
    counts: counts.rows[0] ?? { total: '0', running: '0', failed_24h: '0' },
  });
}

export async function PATCH(request: NextRequest) {
  const { error } = await requirePermission('admin', 'access');
  if (error) return error;
  const body = await request.json().catch(() => ({}));
  const parsed = PatchBody.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json(
      { error: 'Invalid body', details: parsed.error.issues },
      { status: 400 }
    );
  }
  const settings = await updateOvershellVariableName(
    parsed.data.overshellVariableName
  );
  return NextResponse.json({ settings });
}
