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

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

export async function POST(request: Request) {
    const body = await request.json();
    console.log("BODY")
    console.dir({ body })
    const validatedBody = userAddSchema.parse(body);
    validatedBody.person = "6917732face2287b1d901738"
    try {
        const client = new GraphQLClient(endpoint);
        const query = gql`
            mutation CreateUser($input: CreateUserInput!) {
                createUser(input: $input) {
                _id
                password
                tag
                email
                phone
                collectionTokens {
                    default
                    tokens {
                    prefix
                    token
                    }
                }
                person
                }
            }
        `;
        const variables = { input: validatedBody };
        const data = await client.request(query, variables);
        console.log("DATA")
        console.dir({ data })
        return NextResponse.json({ data: data.createUser, status: 200 });
    } catch (err: any) {
        console.error(err);
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}

// export async function POST(request: Request) {

//     const body = await request.json();
//     const validatedBody = userAddSchema.parse(body);
//     console.log("VALIDATED")
//     console.dir({ validatedBody })
//     return NextResponse.json({ data: validatedBody })
// }
