import { createClient } from "@/lib/supabase/server";
import { NextRequest, NextResponse } from "next/server";
import { logger } from "@/lib/logger";
import { withCSRFProtection } from "@/lib/csrf";
import { checkRateLimit, getClientIP, createRateLimitResponse } from "@/lib/rate-limit";

// 20 conversation starts per 15 min window per IP (prevents spam conversation creation)
const START_RATE_LIMIT = 20;
const START_WINDOW_MS = 15 * 60 * 1000;

const handler = async (request: NextRequest) => {
  try {
    const clientIP = getClientIP(request);
    const rateLimit = await checkRateLimit(`messages-start:${clientIP}`, START_RATE_LIMIT, START_WINDOW_MS);

    if (!rateLimit.allowed) {
      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
      return createRateLimitResponse(clientIP, retryAfter);
    }

    const supabase = await createClient();

    // Check if user is authenticated
    const { data: { user }, error: authError } = await supabase.auth.getUser();

    if (authError || !user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { recipientId, initialMessage } = await request.json();

    if (!recipientId) {
      return NextResponse.json(
        { error: "Recipient ID is required" },
        { status: 400 }
      );
    }

    // Validate recipientId is a UUID to prevent filter injection
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
    if (!uuidRegex.test(recipientId)) {
      return NextResponse.json(
        { error: "Invalid recipient ID format" },
        { status: 400 }
      );
    }

    // Validate initial message length
    if (initialMessage && typeof initialMessage === 'string' && initialMessage.length > 5000) {
      return NextResponse.json(
        { error: "Message too long" },
        { status: 400 }
      );
    }

    // Verify recipient exists
    const { data: recipient, error: recipientError } = await supabase
      .from('profiles')
      .select('id, name')
      .eq('id', recipientId)
      .single();

    if (recipientError || !recipient) {
      return NextResponse.json(
        { error: "Recipient not found" },
        { status: 404 }
      );
    }

    // Verify hire relationship: match must be "hired" AND payment must be confirmed
    const { data: hiredMatch, error: matchError } = await supabase
      .from('matches')
      .select(`
        id,
        status,
        worker_id,
        fee_charged,
        jobs!inner(company_id, companies!inner(profile_id))
      `)
      .eq('status', 'hired')
      .or(
        `and(worker_id.eq.${user.id},jobs.companies.profile_id.eq.${recipientId}),` +
        `and(worker_id.eq.${recipientId},jobs.companies.profile_id.eq.${user.id})`
      )
      .limit(1);

    if (matchError) {
      logger.error("Error checking hire status:", matchError);
      return NextResponse.json(
        { error: "Failed to verify hire status" },
        { status: 500 }
      );
    }

    if (!hiredMatch || hiredMatch.length === 0) {
      return NextResponse.json(
        { error: "Messaging is only available after a hire has been confirmed" },
        { status: 403 }
      );
    }

    // Verify payment has been charged for this match
    const matchId = hiredMatch[0].id;
    const { data: payment, error: paymentError } = await supabase
      .from('payments')
      .select('id, status')
      .eq('match_id', matchId)
      .eq('status', 'charged')
      .limit(1);

    if (paymentError) {
      logger.error("Error checking payment status:", paymentError);
      return NextResponse.json(
        { error: "Failed to verify payment status" },
        { status: 500 }
      );
    }

    if (!payment || payment.length === 0) {
      return NextResponse.json(
        { error: "Messaging requires a confirmed payment. Please complete the hire payment first." },
        { status: 403 }
      );
    }

    // Get or create conversation using the database function
    const { data: conversationId, error: conversationError } = await supabase
      .rpc('get_or_create_conversation', {
        user1_id: user.id,
        user2_id: recipientId
      });

    if (conversationError) {
      logger.error("Error creating conversation:", conversationError);
      return NextResponse.json(
        { error: "Failed to create conversation" },
        { status: 500 }
      );
    }

    // If there's an initial message, send it
    if (initialMessage?.trim()) {
      const { error: messageError } = await supabase
        .from('messages')
        .insert({
          conversation_id: conversationId,
          sender_id: user.id,
          content: initialMessage.trim()
        });

      if (messageError) {
        logger.error("Error sending initial message:", messageError);
        // Don't fail the whole request if message fails
      }
    }

    return NextResponse.json({ 
      conversationId,
      message: "Conversation created successfully"
    });
  } catch (error) {
    logger.error("Error in start conversation API:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}

// Apply CSRF protection to the handler
export const POST = withCSRFProtection(handler);
