import { NextRequest } from 'next/server';
import { getSession } from '@/lib/auth';
import { db } from '@/lib/db';
import { createResponse, handleApiError } from '@/src/lib/api';

export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string; revisionId: string }> }) {
  try {
    const { id: portfolioId, revisionId } = await params;
    const session = await getSession();

    const portfolio = await db.portfolio.findFirst({
      where: {
        id: portfolioId,
        OR: [
          { ownerId: session?.user?.id },
          {
            PortfolioContributor: {
              some: {
                userId: session?.user?.id,
              },
            },
          },
        ],
      },
    });

    if (!portfolio) {
      return createResponse(404, 'Portfolio not found');
    }

    const revision = await db.portfolioRevision.findUnique({
      where: {
        id: revisionId,
        portfolioId,
      },
    });

    if (!revision) {
      return createResponse(404, 'Revision not found');
    }

    return createResponse(200, 'Revision fetched successfully', { data: revision });
  } catch (error) {
    return handleApiError(error);
  }
}
