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

/**
 * Create a new version of a work item
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ projectId: string; itemId: string }> }
) {
  try {
    const { projectId, itemId } = await params;
    const { description, changes, createdBy } = await request.json();

    const db = admin.firestore();

    // Get current version count
    const versionsSnapshot = await db
      .collection('projects')
      .doc(projectId)
      .collection('workItems')
      .doc(itemId)
      .collection('versions')
      .orderBy('versionNumber', 'desc')
      .limit(1)
      .get();

    const currentVersion = versionsSnapshot.empty ? 0 : versionsSnapshot.docs[0].data().versionNumber;
    const newVersionNumber = currentVersion + 1;

    // Create new version
    const versionRef = db
      .collection('projects')
      .doc(projectId)
      .collection('workItems')
      .doc(itemId)
      .collection('versions')
      .doc();

    await versionRef.set({
      versionNumber: newVersionNumber,
      description: description || `Version ${newVersionNumber}`,
      changes: changes || {},
      createdBy: createdBy || 'system',
      createdAt: admin.firestore.FieldValue.serverTimestamp(),
    });

    return NextResponse.json({
      success: true,
      versionId: versionRef.id,
      versionNumber: newVersionNumber,
    });
  } catch (error) {
    console.error('Error creating version:', error);
    return NextResponse.json(
      {
        error: 'Failed to create version',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

/**
 * Get version history 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 versionsSnapshot = await db
      .collection('projects')
      .doc(projectId)
      .collection('workItems')
      .doc(itemId)
      .collection('versions')
      .orderBy('versionNumber', 'desc')
      .get();

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

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

