import { createClient } from "@/lib/supabase/server";
import { NextResponse } from "next/server";

export async function POST(request: Request) {
  try {
    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 }
      );
    }

    // 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 }
      );
    }

    // 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) {
      console.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) {
        console.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) {
    console.error("Error in start conversation API:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}
