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

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

export async function POST(request: Request) {
    const body = await request.json();
    const validatedBody = buildAreaAddSchema.parse(body);
    try {
        const client = new GraphQLClient(endpoint);
        const query = gql`
            mutation CreateBuildAreaInput($input: CreateBuildAreaInput!) {
                createBuildArea(input:$input) {
                    _id
                    uuid
                    createdAt
                    areaName
                    areaCode
                    areaType
                    areaDirection
                    areaGrossSize
                    areaNetSize
                    width
                    size
                }
            }
        `;
        const data = await client.request(query, { input: validatedBody });
        return NextResponse.json({ data: data.createBuildArea, status: 200 });
    } catch (err: any) {
        console.error(err);
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}
