import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ForbiddenError, ValidationError } from '@server/errors';
import { getAlertSettings, upsertAlertSettings, AlertSettingsRow } from '@server/services/alert-settings.service';

function toPublic(row: AlertSettingsRow) {
  const { soundEnabled, volume, autoDismiss, showOrders, showBookings, showAiEscalations, browserNotifications } = row;
  return { soundEnabled, volume, autoDismiss, showOrders, showBookings, showAiEscalations, browserNotifications };
}

function clamp(n: number, min: number, max: number) {
  return Math.max(min, Math.min(max, n));
}

function parseBool(v: unknown, fallback: boolean): boolean {
  if (typeof v === 'boolean') return v;
  return fallback;
}

function parseNum(v: unknown, fallback: number, min: number, max: number): number {
  const n = Number(v);
  if (!Number.isFinite(n)) return fallback;
  return clamp(n, min, max);
}

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    if (req.session.role !== 'superadmin' && req.session.role !== 'support') {
      throw new ForbiddenError();
    }
    const { searchParams } = new URL(req.url);
    const restaurantId = searchParams.get('restaurantId');
    if (!restaurantId) throw new ValidationError('restaurantId query param is required');
    const row = await getAlertSettings(restaurantId);
    return NextResponse.json({ settings: toPublic(row) });
  })
);

export const PUT = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    if (req.session.role !== 'superadmin' && req.session.role !== 'support') {
      throw new ForbiddenError();
    }
    const body = await req.json().catch(() => null) as Record<string, unknown> | null;
    if (!body || typeof body !== 'object') throw new ValidationError('Invalid request body');
    const restaurantId = body.restaurantId as string;
    if (!restaurantId || typeof restaurantId !== 'string') throw new ValidationError('restaurantId is required');
    const row = await upsertAlertSettings(restaurantId, {
      soundEnabled: parseBool(body.soundEnabled, true),
      volume: parseNum(body.volume, 70, 0, 100),
      autoDismiss: parseNum(body.autoDismiss, 30, 0, 300),
      showOrders: parseBool(body.showOrders, true),
      showBookings: parseBool(body.showBookings, true),
      showAiEscalations: parseBool(body.showAiEscalations, true),
      browserNotifications: parseBool(body.browserNotifications, false),
    });
    return NextResponse.json({ settings: toPublic(row) });
  })
);
