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

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

export async function POST(request: Request) {
    const body = await request.json();
    const validatedBody = buildTypesAddSchema.parse(body);
    try {
        const client = new GraphQLClient(endpoint);
        const query = gql`
            mutation CreateBuild($input: CreateBuildInput!) {
                createBuild(input: $input) {
                _id
                buildType {
                    token
                    typeToken
                    type
                }
                collectionToken
                info {
                    govAddressCode
                    buildName
                    buildNo
                    maxFloor
                    undergroundFloor
                    buildDate
                    decisionPeriodDate
                    taxNo
                    liftCount
                    heatingSystem
                    coolingSystem
                    hotWaterSystem
                    blockServiceManCount
                    securityServiceManCount
                    garageCount
                    managementRoomId
                }
            }
        }
        `;
        const variables = { input: validatedBody };
        const data = await client.request(query, variables);
        return NextResponse.json({ data: data.createBuild, status: 200 });
    } catch (err: any) {
        console.error(err);
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}
