import { Provide, Inject, Get, Post, Headers } from '@midwayjs/core';
import {
  CoolController,
  CoolTag,
  CoolUrlTag,
  BaseController,
  TagTypes,
} from '@cool-midway/core';
import { Context } from '@midwayjs/koa';
import { RuntimeService } from '../../service/runtime';
import {
  isLoopbackAddress,
  validateRuntimeSecret,
} from '../../../../comm/runtime-secret';

@CoolUrlTag()
@Provide()
@CoolController()
export class BaseAppRuntimeController extends BaseController {
  @Inject()
  runtimeService: RuntimeService;

  @Inject()
  ctx: Context;

  private assertLocalRuntimeAccess(secret?: string | null) {
    const remoteAddress =
      this.ctx.ip || this.ctx.request.ip || this.ctx.req.socket.remoteAddress;
    if (!isLoopbackAddress(remoteAddress)) {
      throw new Error('仅允许本机访问');
    }
    if (!validateRuntimeSecret(process.env.NETA_TRAY_SECRET, secret)) {
      throw new Error('托盘密钥无效');
    }
  }

  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/status', { summary: '本机运行时状态' })
  async status(@Headers('x-neta-tray-secret') secret: string) {
    this.assertLocalRuntimeAccess(secret);
    return this.ok(await this.runtimeService.getRuntimeStatus());
  }

  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/stop', { summary: '本机停止服务' })
  async stop(@Headers('x-neta-tray-secret') secret: string) {
    this.assertLocalRuntimeAccess(secret);
    await this.runtimeService.stopRuntime();
    return this.ok(true);
  }
}
