import { Provide, Inject, Post, Body } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { GeoAccountEntity } from '../../entity/account.js';
import { GeoAccountService } from '../../service/account.js';

@Provide()
@CoolController({
  api: ['delete', 'update', 'info', 'list', 'page'],
  entity: GeoAccountEntity,
  service: GeoAccountService,
  pageQueryOp: {
    keyWordLikeFields: ['name', 'loginAccount', 'sessionName'],
    fieldEq: ['platform', 'loginStatus', 'agentId'],
    addOrderBy: { createTime: 'DESC' },
  },
})
export class AdminGeoAccountController extends BaseController {
  @Inject() accountService: GeoAccountService;

  @Post('/add', { summary: '创建账号（绑定 IP + 关联 agent）' })
  async addAccount(@Body() dto: any) {
    return this.ok(await this.accountService.add(dto));
  }

  @Post('/launch', { summary: '启动浏览器登录（通过 netabrowser-cli daemon）' })
  async launch(@Body('id') id: number, @Body('url') url?: string) {
    return this.ok(await this.accountService.launch(id, url));
  }

  @Post('/close', { summary: '关闭浏览器' })
  async close(@Body('id') id: number) {
    await this.accountService.close(id);
    return this.ok();
  }

  @Post('/captureCookies', { summary: '抓 cookie' })
  async captureCookies(@Body('id') id: number, @Body('domain') domain?: string) {
    return this.ok(await this.accountService.captureCookies(id, domain));
  }

  @Post('/rebindIp', { summary: '重新绑定 IP' })
  async rebindIp(@Body('id') id: number, @Body('newIpId') newIpId: number) {
    await this.accountService.rebindIp(id, newIpId);
    return this.ok();
  }

  @Post('/setProxy', { summary: '设置 IP 模式（本地/第三方双向切换）' })
  async setProxy(@Body() body: { id: number; proxyId?: number | null }) {
    const proxyId = body.proxyId == null || body.proxyId === 0 ? null : body.proxyId;
    await this.accountService.setProxy(body.id, proxyId);
    return this.ok();
  }

  @Post('/resetSession', { summary: '重置会话（清 cookie + 新 sessionName + 新指纹，不动 IP）' })
  async resetSession(@Body('id') id: number) {
    await this.accountService.resetSession(id);
    return this.ok();
  }

  @Post('/deleteAccount', { summary: '逻辑删除账号' })
  async deleteAccount(@Body('id') id: number) {
    await this.accountService.deleteAccount(id);
    return this.ok();
  }
}
