import path from 'path';
import HpsfirController from 'hpsfir-controller';
import HpsfirORM, { HpsfirOrmConnectOption } from 'hpsfir-orm';
import { configure, LOGGER_LEVEL_E, getLogger } from 'hpsfir-log';
import { typeCast } from 'hpsfir-ts-extends';

// 静态导入
import './model/po';
import './model/vo';
import './dao';
import './service';
import './controller';

// 配置日志
configure({
  level: process.env.NODE_ENV === 'development' ? LOGGER_LEVEL_E.debug : LOGGER_LEVEL_E.info,
  enableFile: true,
});

// default可改为自己的项目名称
const logger = getLogger(Symbol('default'));

(async() => {
  const db = require(path.join(process.env.RESOURCE_PATH!, './db.json'));
  if (!db) {
    logger?.error('no db config');
    return;
  }
  await HpsfirORM.connect({
    ...typeCast<HpsfirOrmConnectOption>(db),
    // 同步数据库
    autoSync: {
      enable: true,
      enableUpdateTable: process.env.NODE_ENV === 'development',
      enableDeleteTable: true,
      expectTables: [],
    },
  });

  await HpsfirController.start(Number(process.env.PORT || 3000), {
    // 是否开启跨域
    cors: true,
    corsOptions: {
      headers: ['encrypted', 'Encrypted'],
    },
    swagger: true,
    // 静态文件，可直接访问
    staticPath: path.join(process.env.RESOURCE_PATH!, 'public'),
    globalBaseUrl: process.env.BASE_URL,
  });

})();

process.on('exit', async() => {
  await HpsfirController.distory();
  await HpsfirORM.distory();
});

process.on('uncaughtException', (error) => {
  logger.error('global error:', error);
});
