/**
 * User Notifications API
 * GET - Get user's notifications
 * PATCH - Mark notifications as read/dismissed
 */

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';

export const dynamic = 'force-dynamic';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId');
    const unreadOnly = searchParams.get('unreadOnly') === 'true';
    const limit = parseInt(searchParams.get('limit') || '50');
    const offset = parseInt(searchParams.get('offset') || '0');

    if (!userId) {
      return NextResponse.json(
        { error: 'userId is required' },
        { status: 400 }
      );
    }

    const where: any = { userId };
    if (unreadOnly) {
      where.isRead = false;
      where.isDismissed = false;
    }

    const [notifications, total, unreadCount] = await Promise.all([
      prisma.userNotification.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        take: limit,
        skip: offset,
      }),
      prisma.userNotification.count({ where }),
      prisma.userNotification.count({
        where: { userId, isRead: false, isDismissed: false },
      }),
    ]);

    return NextResponse.json({ notifications, total, unreadCount });
  } catch (error: any) {
    console.error('Error fetching notifications:', error);
    return NextResponse.json(
      { error: 'Failed to fetch notifications', details: error.message },
      { status: 500 }
    );
  }
}

export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, userId, notificationIds } = body;

    if (!userId) {
      return NextResponse.json(
        { error: 'userId is required' },
        { status: 400 }
      );
    }

    const where: any = { userId };
    if (notificationIds?.length) {
      where.id = { in: notificationIds };
    }

    switch (action) {
      case 'read':
        await prisma.userNotification.updateMany({
          where,
          data: { isRead: true, readAt: new Date() },
        });
        return NextResponse.json({ message: 'Notifications marked as read' });

      case 'dismiss':
        await prisma.userNotification.updateMany({
          where,
          data: { isDismissed: true },
        });
        return NextResponse.json({ message: 'Notifications dismissed' });

      case 'read_all':
        await prisma.userNotification.updateMany({
          where: { userId, isRead: false },
          data: { isRead: true, readAt: new Date() },
        });
        return NextResponse.json({ message: 'All notifications marked as read' });

      default:
        return NextResponse.json(
          { error: 'Invalid action. Use: read, dismiss, read_all' },
          { status: 400 }
        );
    }
  } catch (error: any) {
    console.error('Error updating notifications:', error);
    return NextResponse.json(
      { error: 'Failed to update notifications', details: error.message },
      { status: 500 }
    );
  }
}
