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

const getProjectById = async (id: string): Promise<Project | null> => {
  return db.project.findUnique({
    where: { id },
  });
};

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

    const { id } = await params;

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

    if (!project) {
      return createResponse(404, 'Project not found');
    }
    if (session?.user?.role !== 'ADMIN' && project.userId !== session?.user?.id) {
      return createResponse(403, 'Forbidden');
    }

    return createResponse(200, 'Project retrieved', { data: project });
  } catch (error) {
    return handleApiError(error);
  }
}

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

    const { id } = await params;
    const project = await getProjectById(id);

    if (!project) {
      return createResponse(404, 'Project not found');
    }

    if (session?.user?.role !== 'ADMIN' && project.userId !== session?.user?.id) {
      return createResponse(403, 'Forbidden: You do not own this project');
    }

    await db.project.delete({
      where: { id },
    });

    return createResponse(200, `Project ${project.title} deleted`);
  } catch (error) {
    return handleApiError(error);
  }
}

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

    const { id } = await params;
    const data = await req.json();

    const project = await getProjectById(id);

    if (!project) {
      return createResponse(404, 'Project not found');
    }

    if (session?.user?.role !== 'ADMIN' && project.userId !== session?.user?.id) {
      return createResponse(403, 'Forbidden: You do not own this project');
    }

    const portfolioProjects = await db.portfolioProject.findMany({
      where: {
        projectId: id,
        status: 'APPROVED',
        Portfolio: {
          ownerId: { not: session?.user?.id },
        },
      },
    });

    if (portfolioProjects.length > 0) {
      await db.portfolioProject.updateMany({
        where: {
          projectId: id,
          status: 'APPROVED',
        },
        data: {
          status: 'PENDING',
          message: '',
        },
      });
    }


    await db.project.update({
      where: { id },
      data,
    });

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