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

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

    const { id } = await params;

    const config = await req.json();

    await db.$transaction(async (tx) => {
      const portfolio = await tx.portfolio.findFirst({
        where: {
          id,
          OR: [
            { ownerId: session?.user?.id },
            {
              PortfolioContributor: {
                some: {
                  userId: session?.user?.id,
                  status: PortfolioContributorStatus.APPROVED,
                },
              },
            },
          ],
        },
      });

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

      return tx.portfolioRevision.create({
        data: {
          portfolioId: id,
          config,
        },
      });
    });

    return createResponse(201, 'Revision saved successfully');
  } catch (error) {
    return handleApiError(error);
  }
}

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

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

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

    const revisions = await db.portfolioRevision.findMany({
      where: { portfolioId: id },
      orderBy: { createdAt: 'desc' },
    });

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