import {
  Body,
  Controller,
  Get,
  Param,
  Patch,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { ZodResponse } from 'nestjs-zod';
import { Permission } from '@pac/types';
import { RequirePermission } from '../../common/decorators/permissions.decorator';
import {
  ListHostsResponseDto,
  HostSummaryDto,
  UpdateHostRequestDto,
} from './dto/admin.dto';
import { HostsService } from './hosts.service';

/**
 * Admin Platforms — **只读 + 受限更新**(write 操作走 CLI)。
 *
 * 设计:敏感写操作(create / rotate-secret / rotate-push / deactivate)只走
 * `pnpm pac:host <cmd>` CLI(SSH 到 PAC 服务器 + DB 直连)。
 *
 * 这里只保留:
 *   - GET /admin/hosts          列表(将来 web dashboard 查看)
 *   - GET /admin/hosts/:id      详情
 *   - PATCH /admin/hosts/:id    受限更新(actionUrls / pullConfig / active 软停)
 *
 * 不保留(已迁移到 CLI):
 *   - POST /admin/hosts                注册新 host
 *   - POST /admin/hosts/:id/rotate-secret
 *   - POST /admin/hosts/:id/rotate-push-secret
 *   - POST /admin/hosts/:id/deactivate(active=false 通过 PATCH 也可走,这里也提供)
 */
@ApiTags('admin')
@ApiBearerAuth('accessToken')
@Controller('admin/hosts')
@RequirePermission(Permission.PLATFORM_MANAGE)
export class HostsAdminController {
  constructor(private readonly platforms: HostsService) {}

  @Get()
  @ZodResponse({ status: 200, type: ListHostsResponseDto })
  list() {
    return this.platforms.list();
  }

  @Get(':id')
  @ZodResponse({ status: 200, type: HostSummaryDto })
  get(@Param('id') id: string) {
    return this.platforms.get(id);
  }

  @Patch(':id')
  @ZodResponse({ status: 200, type: HostSummaryDto })
  @ApiOperation({
    summary: 'Update host metadata / config (PATCH — actionUrls / pullConfig / active 软停)',
    description:
      '敏感操作(create / rotate / deactivate)走 `pnpm pac:host` CLI;' +
      '本接口只支持改 actionUrls / pullConfig / active 三类非密钥字段。',
  })
  update(@Param('id') id: string, @Body() dto: UpdateHostRequestDto) {
    return this.platforms.update(id, dto);
  }
}
