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