'use server';
import { NextResponse } from 'next/server';
import { GraphQLClient, gql } from 'graphql-request';
import { personUpdateSchema } from './schema';

const endpoint = "http://localhost:3001/graphql";

export async function POST(request: Request) {
    const searchUrl = new URL(request.url);
    const uuid = searchUrl.searchParams.get("uuid") || "";
    const body = await request.json();
    const validatedBody = personUpdateSchema.parse(body);
    if (uuid === "") { return NextResponse.json({ error: "UUID is required" }, { status: 400 }) }
    try {
        const client = new GraphQLClient(endpoint);
        const query = gql`
            mutation UpdateBuildType($uuid: String!, $input: UpdateBuildTypesInput!) {
                updateBuildType(uuid: $uuid, input: $input) {
                    type
                    token
                    typeToken
                    description
                }
            }
        `;
        const variables = { uuid: uuid, input: validatedBody };
        const data = await client.request(query, variables);
        return NextResponse.json({ data: data.updateBuildType, status: 200 });
    } catch (err: any) {
        console.error(err);
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}
