import {
  Controller,
  Post,
  Get,
  Put,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiResponse,
  ApiParam,
} from '@nestjs/swagger';
import { PendingActionService } from '@/application/services/pending-action.service';
import {
  JwtAuthGuard,
  CurrentUser,
  CurrentUserData,
  Public,
} from '@/shared/guards/jwt-auth.guard';
import {
  CreatePendingActionDto,
  UpdatePendingActionDto,
  QueryPendingActionsDto,
  BatchCreatePendingActionDto,
  CompletePendingActionDto,
} from '@/api/dto/request/pending-action.dto';

// ========== 用户端控制器 ==========

@ApiTags('用户待办操作 - 用户端')
@Controller('user/pending-actions')
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
export class PendingActionController {
  constructor(private readonly pendingActionService: PendingActionService) {}

  /**
   * 获取我的待办操作列表
   * 前端登录成功后调用此接口，获取需要执行的特定操作
   */
  @Get()
  @ApiOperation({
    summary: '获取我的待办操作列表',
    description: '获取当前用户待执行的操作列表，按优先级降序排列。前端根据 actionCode 决定跳转到哪个页面。',
  })
  @ApiResponse({
    status: 200,
    description: '成功',
    schema: {
      example: {
        code: 'OK',
        message: 'success',
        data: [
          {
            id: '1',
            userId: '12345',
            actionCode: 'ADOPTION_WIZARD',
            actionParams: { treeType: 'durian', location: '马来西亚' },
            status: 'PENDING',
            priority: 10,
            expiresAt: null,
            createdAt: '2025-01-01T00:00:00.000Z',
          },
        ],
      },
    },
  })
  async getMyPendingActions(@CurrentUser() user: CurrentUserData) {
    const result = await this.pendingActionService.getMyPendingActions(user.userId);
    return {
      code: 'OK',
      message: 'success',
      data: result,
    };
  }

  /**
   * 标记操作完成
   */
  @Post(':id/complete')
  @ApiOperation({
    summary: '标记操作完成',
    description: '用户完成操作后调用此接口标记完成',
  })
  @ApiParam({ name: 'id', description: '操作ID' })
  async completeAction(
    @CurrentUser() user: CurrentUserData,
    @Param('id') actionId: string,
    @Body() dto: CompletePendingActionDto,
  ) {
    const result = await this.pendingActionService.completeAction(
      user.userId,
      actionId,
      dto.resultData,
    );
    return {
      code: 'OK',
      message: '操作已完成',
      data: result,
    };
  }
}

// ========== 后台管理控制器 ==========

@ApiTags('用户待办操作 - 后台管理')
@Controller('admin/pending-actions')
@Public()  // 管理后台通过 admin-service 验证身份，此处跳过 JWT 验证
export class AdminPendingActionController {
  constructor(private readonly pendingActionService: PendingActionService) {}

  /**
   * 创建用户待办操作
   */
  @Post()
  @ApiOperation({
    summary: '创建用户待办操作',
    description: '为指定用户创建一个待办操作，用户登录后会看到此操作',
  })
  async createAction(@Body() dto: CreatePendingActionDto) {
    const result = await this.pendingActionService.createAction(dto, 'admin');
    return {
      code: 'OK',
      message: '操作已创建',
      data: result,
    };
  }

  /**
   * 批量创建用户待办操作
   */
  @Post('batch')
  @ApiOperation({
    summary: '批量创建用户待办操作',
    description: '为多个用户批量创建相同的待办操作',
  })
  async batchCreateActions(@Body() dto: BatchCreatePendingActionDto) {
    const result = await this.pendingActionService.batchCreateActions(dto, 'admin');
    return {
      code: 'OK',
      message: `成功创建 ${result.successCount} 个操作`,
      data: result,
    };
  }

  /**
   * 查询用户待办操作列表
   */
  @Get()
  @ApiOperation({
    summary: '查询用户待办操作列表',
    description: '支持按用户ID、操作代码、状态筛选，分页返回',
  })
  async queryActions(@Query() dto: QueryPendingActionsDto) {
    const result = await this.pendingActionService.queryActions(dto);
    return {
      code: 'OK',
      message: 'success',
      data: result,
    };
  }

  /**
   * 获取单个操作详情
   */
  @Get(':id')
  @ApiOperation({
    summary: '获取操作详情',
  })
  @ApiParam({ name: 'id', description: '操作ID' })
  async getAction(@Param('id') actionId: string) {
    const result = await this.pendingActionService.getAction(actionId);
    return {
      code: 'OK',
      message: 'success',
      data: result,
    };
  }

  /**
   * 更新用户待办操作
   */
  @Put(':id')
  @ApiOperation({
    summary: '更新用户待办操作',
    description: '更新操作的参数、状态、优先级、过期时间等',
  })
  @ApiParam({ name: 'id', description: '操作ID' })
  async updateAction(
    @Param('id') actionId: string,
    @Body() dto: UpdatePendingActionDto,
  ) {
    const result = await this.pendingActionService.updateAction(actionId, dto);
    return {
      code: 'OK',
      message: '操作已更新',
      data: result,
    };
  }

  /**
   * 取消用户待办操作 (软删除)
   */
  @Post(':id/cancel')
  @ApiOperation({
    summary: '取消用户待办操作',
    description: '将操作状态改为 CANCELLED，用户将不再看到此操作',
  })
  @ApiParam({ name: 'id', description: '操作ID' })
  async cancelAction(@Param('id') actionId: string) {
    const result = await this.pendingActionService.cancelAction(actionId);
    return {
      code: 'OK',
      message: '操作已取消',
      data: result,
    };
  }

  /**
   * 删除用户待办操作 (硬删除)
   */
  @Delete(':id')
  @ApiOperation({
    summary: '删除用户待办操作',
    description: '彻底删除操作记录',
  })
  @ApiParam({ name: 'id', description: '操作ID' })
  async deleteAction(@Param('id') actionId: string) {
    await this.pendingActionService.deleteAction(actionId);
    return {
      code: 'OK',
      message: '操作已删除',
    };
  }
}
