import { getServerVercelClient } from '@/src/lib/vercel';
import { createResponse, handleApiError } from '@/lib/api';
import { getSession } from '@/lib/auth';
import { NextRequest } from 'next/server';

export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const session = await getSession();
    const { id } = await params;
    if (!id) {
      return createResponse(400, 'Missing required parameter: id');
    }

    const response = await fetch(`https://api.vercel.com/v9/projects/${id}`, {
      headers: {
        Authorization: `Bearer ${session?.user.vercelAccessToken}`,
      },
    });

    const data = await response.json();

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

export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    if (!id) {
      return createResponse(400, 'Missing required parameter: id');
    }

    const body = await req.json();
    const vercel = await getServerVercelClient();

    await vercel.projects.updateProject({ idOrName: id, requestBody: body });
    return createResponse(200, 'Project updated successfully');
  } catch (error) {
    return handleApiError(error);
  }
}

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

    if (!id) {
      return createResponse(400, 'Missing required parameter: id');
    }

    await vercel.projects.deleteProject({ idOrName: id });
    return createResponse(200, 'Project deleted successfully');
  } catch (error) {
    return handleApiError(error);
  }
}
