'use server';
import { NextResponse } from 'next/server';
import { GraphQLClient, gql } from 'graphql-request';
import { UpdateUserTypesSchema } 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") || "";
    if (uuid === "") { return NextResponse.json({ error: "UUID is required" }, { status: 400 }) }
    const body = await request.json();
    const validatedBody = UpdateUserTypesSchema.parse(body);
    try {
        const client = new GraphQLClient(endpoint);
        const query = gql`mutation UpdateUserType($uuid: String!, $input: UpdateUserTypeInput!) { updateUserType(uuid: $uuid, input: $input) { _id } }`;
        const variables = { uuid: uuid, input: { ...validatedBody } };
        const data = await client.request(query, variables);
        return NextResponse.json({ data: data.updateUserType, status: 200 });
    } catch (err: any) {
        console.error(err);
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}
