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

export async function GET(req: NextRequest) {
  try {
    const session = await getSession();

    const searchTerm = new URL(req.url).searchParams.get('search') ?? '';
    const page = parseInt(new URL(req.url).searchParams.get('page') ?? '1');
    const isAdmin = session?.user?.role === 'ADMIN';
    const where: Prisma.ProjectWhereInput = {
      title: {
        contains: searchTerm,
        mode: 'insensitive',
      },
      ...(!isAdmin && {
        userId: session?.user?.id,
      }),
    };

    const [projectsData, totalProjects] = await db.$transaction([
      db.project.findMany({
        where,
        orderBy: { updatedAt: 'desc' },
        skip: !isAdmin ? undefined : (page - 1) * PAGE_SIZE,
        take: !isAdmin ? undefined : PAGE_SIZE,
      }),
      db.project.count({ where }),
    ]);

    return createResponse(200, 'Projects retrieved', {
      data: projectsData,
      pagination: {
        page,
        total: totalProjects,
        totalPages: Math.ceil(totalProjects / PAGE_SIZE),
      },
    });
  } catch (error) {
    return handleApiError(error);
  }
}

export async function POST(req: NextRequest) {
  try {
    const session = await getSession();

    const data = await req.json();
    const project = await db.project.create({
      data: {
        ...data,
        userId: session?.user?.id,
      },
    });

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