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

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

export async function POST(request: Request) {
    const body = await request.json();
    const { limit, skip, sort, filters } = body;
    try {
        const client = new GraphQLClient(endpoint);
        const query = gql`
            query ListUsers($input: ListArguments!) {
                users(input: $input) {
                    data {
                        _id
                        uuid
                        expiryStarts
                        expiryEnds
                        isConfirmed
                        deleted
                        active
                        crypUuId
                        createdCredentialsToken
                        updatedCredentialsToken
                        confirmedCredentialsToken
                        isNotificationSend
                        isEmailSend
                        refInt
                        refId
                        replicationId
                        expiresAt
                        resetToken
                        password
                        history
                        tag
                        email
                        phone
                        collectionTokens {
                            default
                            tokens {
                                prefix
                                token
                            }
                        }
                        createdAt
                        updatedAt
                    }
                totalCount
                }
            }
        `;
        const variables = { input: { limit, skip, sort, filters } };
        const data = await client.request(query, variables);
        return NextResponse.json({ data: data.users.data, totalCount: data.users.totalCount });
    } catch (err: any) {
        console.error(err);
        return NextResponse.json({ error: err.message }, { status: 500 });
    }
}
