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 }> }) {
  try {
    const { id: portfolioId } = await params;
    const session = await getSession();

    const lastRevision = await db.portfolioRevision.findFirst({
      where: {
        portfolioId,
        Portfolio: {
          OR: [
            { ownerId: session?.user?.id },
            {
              PortfolioContributor: { some: { userId: session?.user?.id } },
            },
          ],
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    if (!lastRevision) {
      const defaultRevision = {
        id: '',
        portfolioId,
        config: {
          elements: [],
        },
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      return createResponse(200, 'Default portfolio revision fetched successfully', { data: defaultRevision });
    }

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