import { NextRequest, NextResponse } from 'next/server';
import admin from '@/lib/firebase/admin';

/**
 * Post a new message/comment on a work item
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string; itemId: string }> }
) {
  try {
    const { projectId, itemId } = await params;
    const { message, author, authorId, type } = await request.json();

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

    const db = admin.firestore();

    // Create new message
    const messageRef = db
      .collection('projects')
      .doc(projectId)
      .collection('workItems')
      .doc(itemId)
      .collection('messages')
      .doc();

    await messageRef.set({
      message,
      author,
      authorId: authorId || 'anonymous',
      type: type || 'comment', // comment, feedback, question, etc.
      createdAt: admin.firestore.FieldValue.serverTimestamp(),
      reactions: [],
    });

    // Update message count on work item metadata
    await db
      .collection('projects')
      .doc(projectId)
      .collection('workItemStates')
      .doc(itemId)
      .set(
        {
          messageCount: admin.firestore.FieldValue.increment(1),
          lastMessageAt: admin.firestore.FieldValue.serverTimestamp(),
        },
        { merge: true }
      );

    return NextResponse.json({
      success: true,
      messageId: messageRef.id,
    });
  } catch (error) {
    console.error('Error posting message:', error);
    return NextResponse.json(
      {
        error: 'Failed to post message',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

/**
 * Get messages/comments for a work item
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string; itemId: string }> }
) {
  try {
    const { projectId, itemId } = await params;
    const db = admin.firestore();

    const messagesSnapshot = await db
      .collection('projects')
      .doc(projectId)
      .collection('workItems')
      .doc(itemId)
      .collection('messages')
      .orderBy('createdAt', 'desc')
      .get();

    const messages = messagesSnapshot.docs.map(doc => ({
      id: doc.id,
      ...doc.data(),
      createdAt: doc.data().createdAt?.toDate().toISOString(),
    }));

    return NextResponse.json({
      messages,
      count: messages.length,
    });
  } catch (error) {
    console.error('Error fetching messages:', error);
    return NextResponse.json(
      {
        error: 'Failed to fetch messages',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

/**
 * Delete a message
 */
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string; itemId: string }> }
) {
  try {
    const { projectId, itemId } = await params;
    const { searchParams } = new URL(request.url);
    const messageId = searchParams.get('messageId');

    if (!messageId) {
      return NextResponse.json(
        { error: 'Message ID is required' },
        { status: 400 }
      );
    }

    const db = admin.firestore();

    // Delete message
    await db
      .collection('projects')
      .doc(projectId)
      .collection('workItems')
      .doc(itemId)
      .collection('messages')
      .doc(messageId)
      .delete();

    // Update message count
    await db
      .collection('projects')
      .doc(projectId)
      .collection('workItemStates')
      .doc(itemId)
      .set(
        {
          messageCount: admin.firestore.FieldValue.increment(-1),
        },
        { merge: true }
      );

    return NextResponse.json({
      success: true,
    });
  } catch (error) {
    console.error('Error deleting message:', error);
    return NextResponse.json(
      {
        error: 'Failed to delete message',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

