import { createClient } from "@/lib/supabase/server";
import { NextRequest, NextResponse } from "next/server";
import { validateCSRFToken, isSameOrigin } from "@/lib/csrf";

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    // CSRF protection: validate same-origin and token
    if (!isSameOrigin(request)) {
      return NextResponse.json({ error: 'Cross-origin request not allowed' }, { status: 403 });
    }
    const csrfValid = await validateCSRFToken(request);
    if (!csrfValid) {
      return NextResponse.json({ error: 'Invalid or missing CSRF token' }, { status: 403 });
    }
    
    const { id: conversationId } = await params;
    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 { content, attachments = [] } = await request.json();

    if (!content?.trim()) {
      return NextResponse.json(
        { error: "Message content is required" },
        { status: 400 }
      );
    }

    // Verify user is a participant in this conversation
    const { data: participant, error: participantError } = await supabase
      .from('conversation_participants')
      .select('id')
      .eq('conversation_id', conversationId)
      .eq('profile_id', user.id)
      .single();

    if (participantError || !participant) {
      return NextResponse.json({ error: "Conversation not found" }, { status: 404 });
    }

    // Insert the message
    const { data: message, error: messageError } = await supabase
      .from('messages')
      .insert({
        conversation_id: conversationId,
        sender_id: user.id,
        content: content.trim(),
        attachments: attachments
      })
      .select(`
        id,
        content,
        sender_id,
        status,
        created_at,
        attachments
      `)
      .single();

    if (messageError) {
      console.error("Error sending message:", messageError);
      return NextResponse.json(
        { error: "Failed to send message" },
        { status: 500 }
      );
    }

    // Get the other participant to send notification
    const { data: otherParticipant } = await supabase
      .from('conversation_participants')
      .select('profile_id')
      .eq('conversation_id', conversationId)
      .neq('profile_id', user.id)
      .single();

    if (otherParticipant) {
      // Create notification for the other participant
      const { data: senderProfile } = await supabase
        .from('profiles')
        .select('name')
        .eq('id', user.id)
        .single();

      await supabase.from('notifications').insert({
        profile_id: otherParticipant.profile_id,
        type: 'system',
        title: 'New message',
        body: `${senderProfile?.name || 'Someone'} sent you a message`,
        data: {
          conversationId: conversationId,
          senderId: user.id
        }
      });
    }

    return NextResponse.json({
      message: {
        id: message.id,
        content: message.content,
        isOwn: true,
        timestamp: message.created_at,
        status: message.status,
        attachments: message.attachments
      }
    });
  } catch (error) {
    console.error("Error in send message API:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}