import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { verifyAdminPermission } from '@/lib/auth';
import { sanitizeString, isValidLength } from '@/lib/validation';
import { checkRateLimit, getRateLimitIdentifier, rateLimitError, RATE_LIMITS } from '@/lib/rate-limit';

export async function POST(request: NextRequest) {
  try {
    // Auth + permission check
    const authResult = await verifyAdminPermission(request, 'canSendNotification');
    if ('error' in authResult) return authResult.error;

    // Rate limit notification sending
    const identifier = `admin-notify:${getRateLimitIdentifier(request)}`;
    const rateLimit = checkRateLimit(identifier, RATE_LIMITS.adminWrite);
    if (!rateLimit.allowed) return rateLimitError(rateLimit.resetTime);

    const { title, message } = await request.json();

    if (!title || !message) {
      return NextResponse.json(
        { success: false, error: 'Title and message are required' },
        { status: 400 }
      );
    }

    // Validate lengths
    if (!isValidLength(title, 1, 200)) {
      return NextResponse.json(
        { success: false, error: 'Title must be between 1 and 200 characters' },
        { status: 400 }
      );
    }

    if (!isValidLength(message, 1, 2000)) {
      return NextResponse.json(
        { success: false, error: 'Message must be between 1 and 2000 characters' },
        { status: 400 }
      );
    }

    // Get all active users
    const users = await db.user.findMany({
      where: { isActive: true },
      select: { id: true },
    });

    // Create notification for each user
    if (users.length > 0) {
      await db.notification.createMany({
        data: users.map((user) => ({
          userId: user.id,
          title: sanitizeString(title),
          message: sanitizeString(message),
          type: 'admin_notice',
        })),
      });
    }

    return NextResponse.json({
      success: true,
      sentCount: users.length,
    });
  } catch (error) {
    console.error('Admin notify error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to send notification' },
      { status: 500 }
    );
  }
}
