import { NextFunction, Request, Response } from 'express';
import { Application } from 'express-serve-static-core';
import { APIError } from '../modules/api-error';

export default (app: Application, prefix: string) => {
  app.all(`/assets/*`, (req, res, next) => next(new APIError(404)));
  app.all(`/${prefix}/*`, (req, res, next) => next(new APIError(404)));

  app.use(`/`, () => { throw new TypeError('Invalid API version number') });
  
  app.use((error: any, req: Request, res: Response, next: NextFunction) => {
    if (res.headersSent)
      return next(error);

    // Handle filesystem/permission errors
    if (error.code === 'EACCES') {
      return res
        .status(500)
        .json({ message: 'Server permission error' });
    }

    // Handle API errors
    const code = error instanceof APIError ? error.code : 500;
    const message = error instanceof APIError ? error.message : 'Internal Server Error';
    
    return res
      .status(code)
      .json({ message });
  });
}