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

export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const search = new URL(req.url).searchParams.get('search') ?? '';
  const session = await getSession();
  const userId = session?.user?.id;

  if (!userId) {
    return createResponse(401, 'Unauthorized');
  }

  try {
    const portfolio = await db.portfolio.findUnique({
      where: { id },
    });

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

    const isOwner = portfolio.ownerId === userId;

    const projects = await db.portfolioProject.findMany({
      where: {
        portfolioId: id,
        Project: {
          title: {
            contains: search,
          },
          ...(isOwner ? {} : { userId }),
        },
      },
      include: {
        Project: {
          include: {
            User: {
              select: {
                id: true,
                username: true,
              },
            },
          },
        },
      },
      orderBy: {
        createdAt: 'asc',
      },
    });

    return createResponse(200, 'Projects retrieved', {
      data: projects.map((pp) => ({
        ...pp.Project,
        status: pp.status,
        createdAt: pp.createdAt,
        isOwner: pp.Project.userId === userId,
        username: pp.Project.User.username,
        message: pp.message,
        User: undefined,
      })),
      isOwner,
    });
  } catch (error) {
    return handleApiError(error);
  }
}

export async function PATCH(req: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    const { projectId, status, message } = await req.json();
    await db.portfolioProject.update({
      where: {
        portfolioId_projectId: { portfolioId: id, projectId },
      },
      data: {
        status,
        message
      },
    });

    return createResponse(200, 'Portfolio project updated');
  } catch (error) {
    return handleApiError(error);
  }
}

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

  try {
    const { projectId } = await req.json();

    const portfolio = await db.portfolio.findUnique({
      where: {
        id: id,
      },
    });

    const status =
      session?.user?.id === portfolio?.ownerId ? PortfolioProjectStatus.APPROVED : PortfolioProjectStatus.PENDING;
    const portfolioProject = await db.portfolioProject.create({
      data: {
        portfolioId: id,
        projectId: projectId,
        status: status,
      },
    });

    return createResponse(200, 'Project added to portfolio', { portfolioProject });
  } catch (error) {
    return handleApiError(error);
  }
}

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

  try {
    const { projectId } = await req.json();

    const portfolioProject = await db.portfolioProject.delete({
      where: {
        portfolioId_projectId: {
          portfolioId: id,
          projectId: projectId,
        },
        Portfolio: {
          ownerId: session?.user?.id,
        },
      },
    });

    return createResponse(200, 'Project removed from portfolio', { portfolioProject });
  } catch (error) {
    return handleApiError(error);
  }
}
