import { NextApiRequest, NextApiResponse } from 'next';
import { odds, serp, sports, coin } from './embed';

export const config = {
    api: {
      bodyParser: {
        sizeLimit: '1mb',
      },
    },
};

type FunctionHandler = any;

const handlers: FunctionHandler = {
  'search': serp,
  'sports_odds': odds,
  'sports_results': sports,
  'coinmarketcap': coin
};

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const args = req.body.args as string;
  const functionName = req.body.name as string;
  const functionInput = JSON.parse(args);
  
  const functionHandler = handlers[functionName];
  
  if (!functionHandler) {
    console.error(`Function "${functionName}" is not supported.`);
    return res.status(500).json({ error: `Function "${functionName}" is not supported.` });
  }
  
  try {
    const result = await functionHandler(functionInput);
    return res.status(200).send(result);
  } catch (error) {
    console.error(error);
    // @ts-ignore
    return res.status(500).json({ error: error.message });
  }
}