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

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

export async function POST(request: Request) {
    const body = await request.json();
    const validatedBody = buildPartsAddSchema.parse({ ...body.data, buildId: body.buildId });
    try {
        const client = new GraphQLClient(endpoint);
        const query = gql`
            mutation CreateBuildParts($input: CreateBuildPartsInput!) {
                createBuildPart(input: $input) {
                    buildId
                    addressGovCode
                    level
                    no
                    code
                    grossSize
                    netSize
                    defaultAccessory
                    humanLivability
                    key
                    directionId
                    typeId
                }
            }
        `;
        const variables = { input: validatedBody };
        const data = await client.request(query, variables);
        return NextResponse.json({ data: data.createBuildPart, status: 200 });
    } catch (err: any) {
        console.error(err);
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}
