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

export async function GET(request: NextRequest) {
  try {
    const { organization, session } = await requireOrganizationAccess({
      permission: PERMISSIONS.notificationsRead
    });
    const { searchParams } = request.nextUrl;
    const page = Number(searchParams.get('page') ?? 1);
    const limit = Number(searchParams.get('limit') ?? 20);
    const status = (searchParams.get('status') ?? 'all') as 'all' | 'unread' | 'read' | 'archived';

    const result = await listNotifications(organization.id, session.user.id, {
      page,
      limit,
      status
    });

    return NextResponse.json({
      success: true,
      time: new Date().toISOString(),
      message: 'Notifications loaded successfully',
      ...result
    });
  } 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 notifications' }, { status: 500 });
  }
}
