import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { ValidationError } from '@server/errors';
import {
  getNotificationPreferences,
  saveNotificationPreferences,
} from '@server/services/notification-preferences.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const prefs = await getNotificationPreferences(
      req.session.restaurantId!,
      req.session.userId!
    );
    return NextResponse.json({ preferences: prefs?.preferences ?? null });
  })
);

export const PUT = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    let body: Awaited<ReturnType<typeof req.json>>;
    try {
      body = await req.json();
    } catch {
      throw new ValidationError('Request body must be valid JSON');
    }
    const { preferences } = body;
    if (!Array.isArray(preferences)) {
      return NextResponse.json({ error: 'preferences must be an array' }, { status: 400 });
    }
    const saved = await saveNotificationPreferences(
      req.session.restaurantId!,
      req.session.userId!,
      preferences
    );
    return NextResponse.json({ preferences: saved?.preferences ?? preferences });
  })
);
