import { NextResponse } from 'next/server';
import { markAllNotificationsAsRead } from '@/features/foundation/notifications/server/inbox-service';
import { PERMISSIONS } from '@/lib/auth/rbac';
import { AuthError, requireOrganizationAccess } from '@/lib/auth/session';

export async function POST() {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.notificationsUpdate
    });
    const affectedCount = await markAllNotificationsAsRead(organization.id, session.user.id);

    return NextResponse.json({
      success: true,
      message: affectedCount > 0 ? 'Notifications marked as read' : 'No unread notifications'
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    if (error instanceof Error) {
      return NextResponse.json({ message: error.message }, { status: 400 });
    }

    return NextResponse.json({ message: 'Unable to update notifications' }, { status: 500 });
  }
}
