import { App, Configuration, Config } from "@midwayjs/decorator";
import { hooks } from "@midwayjs/hooks";
import { ILifeCycle, IMidwayContainer } from "@midwayjs/core";
import { Application } from "@midwayjs/koa";
import { join } from "path";
import bodyParser from "koa-bodyparser";
import session from "koa-session";
import * as redis from "@midwayjs/redis";
import * as axios from "@midwayjs/axios";
import * as cache from "@midwayjs/cache";
import * as view from "@midwayjs/view-nunjucks";
import * as mongoose from "@midwayjs/mongoose";

@Configuration({
  imports: [redis, axios, cache, view, mongoose, hooks()],
  importConfigs: [join(__dirname, "./config/")],
  conflictCheck: true,
})
export default class ContainerLifeCycle implements ILifeCycle {
  @App()
  app: Application;

  @Config("session")
  sessionConfig;

  @Config("keys")
  keys;

  async onReady(container: IMidwayContainer) {
    // 全局错误处理中间件
    this.app.use(await this.app.generateMiddleware("errorMiddleware"));

    this.app.keys = this.keys;

    // session 中间件
    this.app.use(session(this.sessionConfig, this.app));

    // post 请求 bodyParser 中间件
    this.app.use(bodyParser());

    // axios 拦截器
    const httpService = await container.getAsync(axios.HttpService);
    httpService.interceptors.request.use(
      (config) => {
        // Do something before request is sent
        return config;
      },
      (error) => {
        // Do something with request error
        return Promise.reject(error);
      }
    );
  }
}
