import { db } from '@/src/lib/db';
import { NextRequest, NextResponse } from 'next/server';
import { PortfolioProjectStatus } from '@prisma/client';
import { createResponse, handleApiError } from '@/src/lib/api';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ username: string; portfolioTitle: string }> }
) {
  const { username, portfolioTitle } = await params;

  if (!username || !portfolioTitle) {
    return NextResponse.json({ error: 'Missing required parameters' }, { status: 400 });
  }

  const user = await db.user.findFirst({
    where: {
      username: {
        equals: decodeURIComponent(username),
        mode: 'insensitive',
      },
    },
  });

  try {
    const portfolioData = await db.portfolio.findFirst({
      where: {
        title: {
          equals: decodeURIComponent(portfolioTitle),
          mode: 'insensitive',
        },
        ownerId: user?.id,
        is_published: true,
      },
    });

    const projects = await db.portfolioProject.findMany({
      where: {
        portfolioId: portfolioData?.id,
        status: PortfolioProjectStatus.APPROVED,
      },
      include: {
        Project: true,
      },
    });

    const revisionData = await db.portfolioRevision.findFirst({
      where: {
        portfolioId: portfolioData?.id,
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    if (!portfolioData || !revisionData || !projects) {
      return createResponse(404, 'Portfolio not found or not published');
    }

    return createResponse(200, 'Portfolio retrieved', {
      portfolio: revisionData,
      projects: projects.map((pp) => ({
        ...pp.Project,
        status: pp.status,
        createdAt: pp.createdAt,
      })),
    });
  } catch (error) {
    return handleApiError(error);
  }
}
