// packages/backend/src/modules/netaclaw/browser-daemon/controller/admin/session.ts
import { Provide, Inject, Controller, Post, Get, Body } from '@midwayjs/core';
import { CoolTag, CoolUrlTag, TagTypes } from '@cool-midway/core';
import { Context } from '@midwayjs/koa';
import { BrowserDaemonService } from '../../service/daemon.service.js';

@Provide()
@CoolUrlTag()
@Controller('/admin/browser-daemon')
export class AdminBrowserDaemonSessionController {
  @Inject() daemonService: BrowserDaemonService;
  @Inject() ctx: Context;

  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/open')
  async open(@Body() dto: any) {
    try {
      const r = await this.daemonService.open(dto);
      return { code: 1000, data: r };
    } catch (e: any) {
      this.ctx.status = e.statusCode ?? 400;
      return { code: 1002, error: e.message, retryAfter: e.retryAfter };
    }
  }

  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/close')
  async close(@Body('sessionName') sessionName: string) {
    await this.daemonService.close(sessionName);
    return { code: 1000, data: { ok: true } };
  }

  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/list')
  async list() {
    return { code: 1000, data: this.daemonService.list() };
  }

  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Get('/stats')
  async stats() {
    return { code: 1000, data: this.daemonService.getStats() };
  }
}
