import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET(req: NextRequest) {
  try {
    console.log('[Notification API] Attempting to get session...');
    
    let session;
    try {
      session = await getServerSession(authOptions);
      console.log('[Notification API] Session retrieved:', {
        hasSession: !!session,
        hasUser: !!session?.user,
        userEmail: session?.user?.email,
        userId: (session?.user as any)?.id
      });
    } catch (sessionError) {
      console.error('[Notification API] Session error:', sessionError);
      return NextResponse.json(
        { 
          error: 'Session validation failed', 
          details: sessionError instanceof Error ? sessionError.message : 'Unknown session error'
        },
        { status: 401 }
      );
    }
    
    if (!session?.user?.email) {
      console.log('[Notification API] No valid session or user email');
      return NextResponse.json(
        { error: 'Unauthorized - no valid session' },
        { status: 401 }
      );
    }

    const user = await prisma.user.findUnique({
      where: { email: session.user.email }
    });

    if (!user) {
      return NextResponse.json(
        { error: 'User not found' },
        { status: 404 }
      );
    }

    const unreadCount = await prisma.notification.count({
      where: {
        userId: user.id,
        isRead: false,
        type: {
          not: 'message_received' // Exclude message notifications from notification bell count
        }
      }
    });

    return NextResponse.json({
      success: true,
      data: { unreadCount }
    });

  } catch (error) {
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to fetch unread count',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}