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

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const body = await request.json();

    const { title, content, type, source } = body;

    if (!title || !content) {
      return NextResponse.json(
        { error: 'Title and content are required' },
        { status: 400 }
      );
    }

    // Create document
    const docRef = await adminDb
      .collection('projects')
      .doc(projectId)
      .collection('documents')
      .add({
        title,
        content,
        type: type || 'text', // text, markdown, pdf, etc.
        source: source || 'manual_upload', // chatgpt, slack, manual_upload, etc.
        uploadedAt: new Date().toISOString(),
        wordCount: content.split(/\s+/).length,
        charCount: content.length
      });

    console.log(`✅ Document uploaded: ${title} (${docRef.id})`);

    return NextResponse.json({
      success: true,
      documentId: docRef.id,
      message: 'Document uploaded successfully'
    });

  } catch (error) {
    console.error('Error uploading document:', error);
    return NextResponse.json(
      { 
        error: 'Failed to upload document',
        details: error instanceof Error ? error.message : String(error)
      },
      { status: 500 }
    );
  }
}

// Batch upload multiple documents
export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;
    const body = await request.json();

    const { documents } = body;

    if (!Array.isArray(documents) || documents.length === 0) {
      return NextResponse.json(
        { error: 'Documents array is required' },
        { status: 400 }
      );
    }

    const uploadedDocs = [];

    for (const doc of documents) {
      if (!doc.title || !doc.content) {
        continue; // Skip invalid documents
      }

      const docRef = await adminDb
        .collection('projects')
        .doc(projectId)
        .collection('documents')
        .add({
          title: doc.title,
          content: doc.content,
          type: doc.type || 'text',
          source: doc.source || 'batch_upload',
          uploadedAt: new Date().toISOString(),
          wordCount: doc.content.split(/\s+/).length,
          charCount: doc.content.length,
          metadata: doc.metadata || {}
        });

      uploadedDocs.push({
        id: docRef.id,
        title: doc.title
      });
    }

    console.log(`✅ Batch uploaded ${uploadedDocs.length} documents`);

    return NextResponse.json({
      success: true,
      uploadedCount: uploadedDocs.length,
      documents: uploadedDocs
    });

  } catch (error) {
    console.error('Error batch uploading documents:', error);
    return NextResponse.json(
      { 
        error: 'Failed to batch upload documents',
        details: error instanceof Error ? error.message : String(error)
      },
      { status: 500 }
    );
  }
}

// Get all documents
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string }> }
) {
  try {
    const { projectId } = await params;

    const documentsSnapshot = await adminDb
      .collection('projects')
      .doc(projectId)
      .collection('documents')
      .orderBy('uploadedAt', 'desc')
      .get();

    const documents = documentsSnapshot.docs.map(doc => ({
      id: doc.id,
      ...doc.data()
    }));

    return NextResponse.json({
      total: documents.length,
      documents
    });

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

