import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
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) => {
    const body = await req.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 });
  })
);
