import { Client, Users } from 'node-appwrite';
import validator from 'validator';

// This is your Appwrite function
// It's executed each time we get a request
export default async ({ req, res, log, error }) => {
  const client = new Client()
    .setEndpoint('https://appwrite.oys.undock.ca/v1')
    .setProject(process.env.APPWRITE_FUNCTION_PROJECT_ID)
    .setKey(process.env.APPWRITE_API_KEY);

  // You can log messages to the console
  // log('Hello, Logs!');

  // If something goes wrong, log an error
  //   error('Hello, Errors!');

  // The `req` object contains the request data
  if (req.headers['x-appwrite-user-jwt']) {
    const [_,path,userId] = req.path.split('/')

    if (req.method === 'GET' && path === 'userinfo' && validator.isByteLength(userId,{min: 1, max: 32})) {
      // Send a response with the res object helpers
      // `res.send()` dispatches a string back to the client

      const users = new Users(client);

      const user = await users.get(userId);
      return res.json({'name':user.name});
    } else {
      error('Query Error');
      return res.send("Query Error", 404);
    }
  } else {
    return res.send('Unauthorized',403)
  }
};
