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

export async function GET(
  request: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    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 });
    }

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

    // Get conversation details with other participant info
    const { data: conversationData, error: conversationError } = await supabase
      .from('conversation_participants')
      .select(`
        profile_id,
        profiles!inner(
          id,
          name,
          avatar_url,
          type
        )
      `)
      .eq('conversation_id', conversationId)
      .neq('profile_id', user.id)
      .single();

    if (conversationError || !conversationData) {
      return NextResponse.json(
        { error: "Failed to fetch conversation details" },
        { status: 500 }
      );
    }

    // Get messages in this conversation
    const { data: messages, error: messagesError } = await supabase
      .from('messages')
      .select(`
        id,
        content,
        sender_id,
        status,
        created_at,
        attachments
      `)
      .eq('conversation_id', conversationId)
      .order('created_at', { ascending: true });

    if (messagesError) {
      return NextResponse.json(
        { error: "Failed to fetch messages" },
        { status: 500 }
      );
    }

    // Update last_read_at for the current user
    await supabase
      .from('conversation_participants')
      .update({ last_read_at: new Date().toISOString() })
      .eq('conversation_id', conversationId)
      .eq('profile_id', user.id);

    // Cast profiles to single object (inner join guarantees single row)
    const profile = conversationData.profiles as unknown as {
      id: string;
      name: string;
      avatar_url: string | null;
      type: string;
    };
    
    return NextResponse.json({
      conversation: {
        id: conversationId,
        otherParticipant: {
          id: profile.id,
          name: profile.name,
          avatar: profile.avatar_url,
          type: profile.type,
          isOnline: true // TODO: Implement online status
        },
        messages: messages?.map(msg => ({
          id: msg.id,
          content: msg.content,
          isOwn: msg.sender_id === user.id,
          timestamp: msg.created_at,
          status: msg.status,
          attachments: msg.attachments
        })) || []
      }
    });
  } catch (error) {
    console.error("Error in conversation API:", error);
    return NextResponse.json(
      { error: "Internal server error" },
      { status: 500 }
    );
  }
}