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

export async function GET() {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.notificationsRead
    });
    const unreadCount = await getUnreadNotificationCount(organization.id, session.user.id);

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Unread notification count loaded successfully',
      unreadCount
    });
  } 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 load unread notification count' },
      { status: 500 }
    );
  }
}
