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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const senderId = searchParams.get('senderId');
    const receiverId = searchParams.get('receiverId');
    const page = parseInt(searchParams.get('page') || '1');
    const limit = Math.min(100, Math.max(1, parseInt(searchParams.get('limit') || '20')));

    if (!senderId || !receiverId) {
      return NextResponse.json(
        { error: 'senderId and receiverId are required' },
        { status: 400 }
      );
    }

    if (!isValidId(senderId) || !isValidId(receiverId)) {
      return NextResponse.json(
        { error: 'Invalid sender or receiver ID format' },
        { status: 400 }
      );
    }

    const skip = (page - 1) * limit;

    const [messages, total] = await Promise.all([
      db.message.findMany({
        where: {
          OR: [
            { senderId, receiverId },
            { senderId: receiverId, receiverId: senderId },
          ],
        },
        orderBy: { createdAt: 'asc' },
        skip,
        take: limit,
      }),
      db.message.count({
        where: {
          OR: [
            { senderId, receiverId },
            { senderId: receiverId, receiverId: senderId },
          ],
        },
      }),
    ]);

    // Mark unread messages as read
    await db.message.updateMany({
      where: {
        senderId: receiverId,
        receiverId: senderId,
        isRead: false,
      },
      data: { isRead: true },
    });

    return NextResponse.json({
      messages,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error('Messages GET error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    // Rate limit message sending
    const identifier = `messages:${getRateLimitIdentifier(request)}`;
    const rateLimit = checkRateLimit(identifier, RATE_LIMITS.api);
    if (!rateLimit.allowed) return rateLimitError(rateLimit.resetTime);

    const body = await request.json();
    const { senderId, receiverId, content, messageType } = body;

    if (!senderId || !receiverId || !content) {
      return NextResponse.json(
        { error: 'Missing required fields: senderId, receiverId, content' },
        { status: 400 }
      );
    }

    if (!isValidId(senderId) || !isValidId(receiverId)) {
      return NextResponse.json(
        { error: 'Invalid sender or receiver ID format' },
        { status: 400 }
      );
    }

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

    const msgType = messageType || 'text';
    if (!isValidMessageType(msgType)) {
      return NextResponse.json(
        { error: 'Invalid message type' },
        { status: 400 }
      );
    }

    const message = await db.message.create({
      data: {
        senderId,
        receiverId,
        content: sanitizeString(content),
        messageType: msgType,
      },
    });

    return NextResponse.json({ message }, { status: 201 });
  } catch (error) {
    console.error('Messages POST error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
