import express, { Request, Response, NextFunction } from 'express';
import path from 'path';
import logger from 'morgan';
import bodyParser from 'body-parser';
import { renderFile } from 'ejs';

import indexRouter from './routes/index';

const app = express();

// view engine setup
app.set('views', path.join(process.cwd(), 'public'));
app.set('view engine', 'html');
app.engine('html', renderFile);

app.use(logger('dev'));
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(process.cwd(), 'public')));

app.use((req: Request, res: Response, next: NextFunction) => {
  // @ts-ignore
  res.success = function (data: any) {
    res.json({
      code: 0,
      msg: '操作成功',
      data: data,
    });
  };

  // @ts-ignore
  res.fail = function (message: string) {
    res.json({
      code: 1,
      msg: message,
    });
  };
  next();
});

app.use('/api', indexRouter);

app.use('*', (req: Request, res: Response) => {
  res.render('index', { title: 'Express' });
});

// error handler
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  // res.render('error');
  res.send(err);
});

export default app;
