import { NextResponse } from 'next/server';
import { withErrorHandler } from '@server/middleware/withErrorHandler';
import { withAuth, AuthedRequest } from '@server/middleware/withAuth';
import { listNotifications } from '@server/services/notifications.service';

export const GET = withErrorHandler(
  withAuth(async (req: AuthedRequest) => {
    const { restaurantId, userId } = req.session;
    const url = new URL(req.url);
    const p = url.searchParams;

    const requestedUserId = p.get('user_id');
    const resolvedUserId = req.session.role === 'admin' && requestedUserId
      ? requestedUserId
      : userId;

    const result = await listNotifications({
      restaurantId: restaurantId!,
      userId: resolvedUserId,
      isRead: p.has('is_read') ? p.get('is_read') === 'true' : undefined,
      type: p.get('type') ?? undefined,
      page: parseInt(p.get('page') ?? '1', 10),
      limit: parseInt(p.get('limit') ?? '30', 10),
    });

    return NextResponse.json({ notifications: result.data, unread: result.unread, total: result.total, page: result.page, limit: result.limit, pages: result.pages });
  })
);
