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