import devtools from '../../lib/devtools.js';
import fs from 'fs';

export const get = async (req, res) => {
  if(process.env.DANGER_ADMIN === "1") {
    // the devtools module contains all of the errors from the service/api.js for api and sockets
    // but to get at the svelte errors we have to read debug/errors/svelte.json

    let svelte_errors = [];

    try {
      const build_config = JSON.parse(fs.readFileSync("./build.json"));

      for(let config of build_config) {
        if(config.errorFile) {
          const meta = JSON.parse(fs.readFileSync(config.errorFile));
          // BUG: probably should just return this raw but let's try only errors/warnings
          svelte_errors = svelte_errors.concat(meta.errors);
        }
      }
    } catch(error) {
      return res.status(404).json({message: "File not found."});
    }

    return res.status(200).json({
        api: devtools.api,
        sockets: devtools.sockets,
        errors: devtools.errors.concat(svelte_errors)});
  } else {
    return res.status(404).json({ message: "Not Found."});
  }
}
