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

export async function POST(
  _request: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.notificationsUpdate
    });
    const { id } = await context.params;
    const notification = await markNotificationAsRead(organization.id, session.user.id, id);

    if (!notification) {
      return NextResponse.json({ message: 'Notification not found' }, { status: 404 });
    }

    return NextResponse.json({
      success: true,
      message: 'Notification marked as read'
    });
  } 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 notification' }, { status: 500 });
  }
}
