import { Category, sequelize } from './model';
import formidable from 'formidable';
var randomize = require('randomatic');
import rimraf from 'fs-extra';
import { csrf } from 'src/lib/csrf';
const path = require('path');
const fs = require('fs');

async function add(req) {
  try {
    const form = formidable({});

    await sequelize.authenticate();

    let fields;
    let files;
    [fields, files] = await form.parse(req);

    let name = fields['name'][0];
    let description = fields['description'][0];

    let category = await Category.create({
      name,
      description,
    });

    return { status: 'OK', category };
  } catch (error) {
    console.error(error);
  }
}

async function handler(req, res) {
  try {
    let result = await add(req);

    return res.status(200).send(result);
  } catch (err) {
    console.log(err);
    res.status(200).send({ status: 'error', message: 'add error' });
  }
}

export const config = {
  api: {
    bodyParser: false,
  },
};

export default csrf(handler);
