import { getServerVercelClient } from '@/src/lib/vercel';
import { createResponse, handleApiError } from '@/src/lib/api';
import { CreateProjectEnv2Target } from '@vercel/sdk/models/createprojectenvop.js';
import { NextRequest } from 'next/server';

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

    const search = new URL(req.url).searchParams.get('search') ?? '';
    const projects = await vercel.projects.getProjects({
      search: search,
    });

    return createResponse(200, 'Projects retrieved', {
      data: projects.projects,
    });
  } catch (error) {
    return handleApiError(error);
  }
}

function sanitizeEmptyStrings<T extends object>(obj: T): T {
  if (!obj || typeof obj !== 'object') return obj;

  return Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, value === '' ? undefined : value])) as T;
}

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

    const project = await vercel.projects.createProject({
      requestBody: sanitizeEmptyStrings({
        name: body.name.toLowerCase(),
        environmentVariables: body.env,
        gitRepository: body.gitRepository,
        framework: body.framework ?? undefined,
        buildCommand: body.buildCommand,
        outputDirectory: body.outputDirectory,
        installCommand: body.installCommand,
        rootDirectory: body.rootDirectory,
      }),
    });

    if (body.env && body.env.length > 0) {
      const envVars = Object.entries(body.env).map(([key, value]) => ({
        key,
        value: value as string,
        type: 'encrypted' as const,
        target: ['production', 'preview', 'development'] as CreateProjectEnv2Target[],
        customEnvironmentIds: [],
      }));

      await vercel.projects.createProjectEnv({
        idOrName: project.id,
        upsert: 'true',
        requestBody: envVars,
      });
    }

    const deployment = await vercel.deployments.createDeployment({
      requestBody: {
        gitSource: {
          type: body.gitRepository.type,
          repoId: body.gitRepository.type === 'github' ? body.gitRepository.id : undefined,
          projectId:
            body.gitRepository.type === 'gitlab' && project.link && 'projectId' in project.link
              ? project.link.projectId
              : undefined,
          repoUuid: body.gitRepository.type === 'bitbucket' ? body.gitRepository.id : undefined,
          ref: body.gitRepository.ref,
        },
        projectSettings: {
          framework: body.framework ?? null,
          buildCommand: body.buildCommand ?? null,
          outputDirectory: body.outputDirectory ?? null,
          installCommand: body.installCommand ?? null,
          rootDirectory: body.rootDirectory ?? null,
        },
        name: body.name.toLowerCase(),
        target: 'production',
      },
    });

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