const path = require("path");

const _ = require("lodash");
const logger = require("../utils/logger");
require("dotenv").config({
  path: path.resolve(
    process.cwd(),
    `.env.${process.env.NODE_ENV || "development"}`
  ),
});

const client = require("../graphql-client/graphql-client").client;

exports.createAssociation = async (req, res) => {
  logger.log("admin-create-association", "ADMIN", req.user.email, null, {
    request: req.body,
    ioadmin: true,
  });
  const { shopid, authlevel, useremail } = req.body;

  const result = await client.request(
    `mutation INSERT_ASSOCIATION($assoc: associations_insert_input!){
  insert_associations_one(object:$assoc){
    id
    authlevel
    useremail
    active
  }
}`,
    {
      assoc: { shopid, authlevel, useremail, active: false },
    }
  );
  res.json(result);
};
exports.createShop = async (req, res) => {
  logger.log("admin-create-shop", "ADMIN", req.user.email, null, {
    request: req.body,
    ioadmin: true,
  });
  const { bodyshop, ronum } = req.body;

  try {
    const result = await client.request(
      `mutation INSERT_BODYSHOPS($bs: bodyshops_insert_input!){
  insert_bodyshops_one(object:$bs){
    id
   
  }
}`,
      {
        bs: {
          ...bodyshop,
          counters: {
            data: [
              { countertype: "ronum", count: ronum },
              { countertype: "ihbnum", count: 1 },
              { countertype: "paymentnum", count: 1 },
            ],
          },
        },
      }
    );
    res.json(result);
  } catch (error) {
    res.status(500).json(error);
  }
};
exports.updateCounter = async (req, res) => {
  logger.log("admin-update-counter", "ADMIN", req.user.email, null, {
    request: req.body,
    ioadmin: true,
  });
  const { id, counter } = req.body;

  try {
    const result = await client.request(
      `mutation UPDATE_COUNTER($id: uuid!, $counter: counters_set_input!) {
      update_counters_by_pk(pk_columns: { id: $id }, _set: $counter) {
        id
        countertype
        count
        prefix
      }
    }`,
      {
        id,
        counter,
      }
    );
    res.json(result);
  } catch (error) {
    res.status(500).json(error);
  }
};
exports.updateShop = async (req, res) => {
  logger.log("admin-update-shop", "ADMIN", req.user.email, null, {
    request: req.body,
    ioadmin: true,
  });
  const { id, bodyshop } = req.body;

  try {
    const result = await client.request(
      `mutation UPDATE_BODYSHOP($id: uuid!, $bodyshop: bodyshops_set_input!) {
      update_bodyshops_by_pk(pk_columns: { id: $id }, _set: $bodyshop) {
        id

      }
    }`,
      {
        id,
        bodyshop,
      }
    );
    res.json(result);
  } catch (error) {
    res.status(500).json(error);
  }
};
