import { Controller, Get } from '@nestjs/common';
import { NoAuthToken } from 'src/common/decorator/no-token.decorator';
import { User } from 'src/system/entities/user.entity';
import { DataSource } from 'typeorm';
import dataSources from './data-source';

@Controller('initialize')
export class InitializeController {
  constructor(private dataSource: DataSource) {}

  hasInitSystem = false;

  @Get()
  @NoAuthToken()
  async initialize() {
    return this.dataSource.transaction(async (manager) => {
      if (this.hasInitSystem) throw '系统已初始化';
      this.hasInitSystem = true;

      const user = await manager.findOneBy(User, { username: 'admin' });
      if (user) throw '系统已初始化';

      for (const [entity, dataList] of dataSources) {
        manager.insert(entity as any, dataList);
      }
      return '系统数据初始化成功';
    });
  }
}
