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

export async function POST(req: NextRequest) {
  try {
    const vercel = await getServerVercelClient();

    const body = await req.json();

    const requestBody = {
      name: body.name,
      target: 'production' as const,
      projectSettings: {
        buildCommand: body.buildCommand ?? null,
        installCommand: body.installCommand ?? null,
        outputDirectory: body.outputDirectory ?? null,
        framework: body.framework ?? null,
        rootDirectory: body.rootDirectory ?? null,
      },
      env: body.environmentVariables ?? {},
      gitSource: {
        type: 'github' as const,
        repoId: body.repoId,
        ref: body.ref,
      },
    };
    const deployment = await vercel.deployments.createDeployment({
      requestBody,
    });

    return createResponse(200, 'Deployment created successfully', {
      data: deployment,
    });
  } catch (error) {
    return handleApiError(error);
  }
}

export async function GET() {
  try {
    const vercel = await getServerVercelClient();
    const deployments = await vercel.deployments.getDeployments({});
    return createResponse(200, 'Deployments retrieved successfully', {
      data: deployments,
    });
  } catch (error) {
    return handleApiError(error);
  }
}
