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

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);
}

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

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    if (!req.session.restaurantId) throw new ValidationError('No restaurant context');
    const row = await getAlertSettings(req.session.restaurantId);
    return NextResponse.json({ settings: toPublic(row) });
  })
);

export const PUT = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    if (!req.session.restaurantId) throw new ValidationError('No restaurant context');
    const body = await req.json().catch(() => null) as Record<string, unknown> | null;
    if (!body || typeof body !== 'object') throw new ValidationError('Invalid request body');
    const row = await upsertAlertSettings(req.session.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) });
  })
);
