import { Inject } from "@midwayjs/decorator";
import { RedisService } from "@midwayjs/redis";
import { HttpService } from "@midwayjs/axios";
import CacheService from "@/apis/service/cache";
import { MongooseConnectionServiceFactory } from "@midwayjs/mongoose";
import ModelName from "@/constants/dbEnum";
import getSchemaByModelName from "@/apis/model";

// 抽象
export default abstract class BaseService {
  @Inject()
  redisService: RedisService;

  @Inject()
  httpService: HttpService;

  @Inject()
  cacheService: CacheService;

  @Inject()
  connFactory: MongooseConnectionServiceFactory;

  // 获取数据库的指定 Model
  getModel<T>(modelName: ModelName, dbName?: string) {
    let conn;
    if (!dbName) {
      conn = this.connFactory.get("default");
    } else {
      conn = this.connFactory.get(dbName);
    }
    const schema = getSchemaByModelName(modelName);
    return conn.model<T>(modelName, schema, modelName);
  }

  // 获取数据库指定的 Collection
  getCollection(modelName: ModelName, dbName?: string) {
    let conn;
    if (!dbName) {
      conn = this.connFactory.get("default");
    } else {
      conn = this.connFactory.get(dbName);
    }
    return conn.collection(modelName);
  }
}
