import { Router } from 'express';
import Joi from 'joi';

import logger from '../libs/logger';
import { authenticate } from '../libs/security';
import { createToken } from '../integrations/arcblock/token';

const router = Router();
const auth = authenticate({ component: true, roles: ['owner', 'admin'] });

const createTokenSchema = Joi.object({
  name: Joi.string().max(64).required(),
  symbol: Joi.string().max(16).required(),
  decimal: Joi.number().integer().min(2).max(18).default(10),
}).unknown(true);

router.post('/', auth, async (req, res) => {
  try {
    const { error } = createTokenSchema.validate(req.body);
    if (error) {
      return res.status(400).json({ error: `Token create request invalid: ${error.message}` });
    }

    const tokenFactoryState = await createToken({
      name: req.body.name,
      symbol: req.body.symbol,
      decimal: req.body.decimal,
      livemode: !!req.livemode,
    });

    return res.json(tokenFactoryState);
  } catch (err) {
    logger.error('create credit token failed', { error: err?.message, request: req.body });
    return res.status(400).json({ error: err?.message });
  }
});

export default router;
