import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { MemoryService } from '../../application/services/memory.service';
import { MemoryType } from '../../domain/entities/user-memory.entity';
import { ExperienceType } from '../../domain/entities/system-experience.entity';
import {
  SaveMemoryDto,
  SearchMemoryDto,
  ExtractExperienceDto,
  MemoryFeedbackDto,
} from '../../application/dtos/memory.dto';

@Controller('memory')
export class MemoryController {
  constructor(private memoryService: MemoryService) {}

  // ========== 用户记忆 ==========

  /**
   * 保存用户记忆
   */
  @Post('user')
  @HttpCode(HttpStatus.CREATED)
  async saveUserMemory(@Body() dto: SaveMemoryDto) {
    const memory = await this.memoryService.saveUserMemory(dto);
    return {
      success: true,
      data: memory,
    };
  }

  /**
   * 搜索用户相关记忆
   */
  @Post('user/search')
  async searchUserMemories(@Body() dto: SearchMemoryDto) {
    const memories = await this.memoryService.getUserRelevantMemories(
      dto.userId,
      dto.query,
      { limit: dto.limit },
    );
    return {
      success: true,
      data: memories,
    };
  }

  /**
   * 获取用户最重要的记忆
   */
  @Get('user/:userId/top')
  async getUserTopMemories(
    @Param('userId') userId: string,
    @Query('limit') limit?: string,
  ) {
    const memories = await this.memoryService.getUserTopMemories(
      userId,
      limit ? parseInt(limit) : 5,
    );
    return {
      success: true,
      data: memories,
    };
  }

  /**
   * 获取用户所有记忆
   */
  @Get('user/:userId')
  async getUserMemories(
    @Param('userId') userId: string,
    @Query('type') memoryType?: MemoryType,
    @Query('includeExpired') includeExpired?: string,
  ) {
    const memories = await this.memoryService.getUserMemories(userId, {
      memoryType,
      includeExpired: includeExpired === 'true',
    });
    return {
      success: true,
      data: memories,
    };
  }

  /**
   * 更新记忆重要性
   */
  @Put('user/memory/:id/importance')
  async updateMemoryImportance(
    @Param('id') id: string,
    @Body() body: { importance: number },
  ) {
    await this.memoryService.updateMemoryImportance(id, body.importance);
    return {
      success: true,
      message: 'Importance updated',
    };
  }

  /**
   * 标记记忆为过期
   */
  @Post('user/memory/:id/expire')
  async expireMemory(@Param('id') id: string) {
    await this.memoryService.expireMemory(id);
    return {
      success: true,
      message: 'Memory expired',
    };
  }

  /**
   * 删除用户所有记忆
   */
  @Delete('user/:userId')
  @HttpCode(HttpStatus.NO_CONTENT)
  async deleteUserMemories(@Param('userId') userId: string) {
    await this.memoryService.deleteUserMemories(userId);
  }

  /**
   * 获取用户时间线
   */
  @Get('user/:userId/timeline')
  async getUserTimeline(
    @Param('userId') userId: string,
    @Query('limit') limit?: string,
  ) {
    const timeline = await this.memoryService.getUserTimeline(userId, {
      limit: limit ? parseInt(limit) : 20,
    });
    return {
      success: true,
      data: timeline,
    };
  }

  // ========== 系统经验 ==========

  /**
   * 提取并保存经验
   */
  @Post('experience')
  @HttpCode(HttpStatus.CREATED)
  async extractExperience(@Body() dto: ExtractExperienceDto) {
    const experience = await this.memoryService.extractAndSaveExperience(dto);
    return {
      success: true,
      data: experience,
    };
  }

  /**
   * 搜索相关经验
   */
  @Post('experience/search')
  async searchExperiences(@Body() body: {
    query: string;
    experienceType?: ExperienceType;
    category?: string;
    limit?: number;
  }) {
    const experiences = await this.memoryService.getRelevantExperiences(body.query, {
      experienceType: body.experienceType,
      category: body.category,
      limit: body.limit,
    });
    return {
      success: true,
      data: experiences,
    };
  }

  /**
   * 获取待验证的经验
   */
  @Get('experience/pending')
  async getPendingExperiences(
    @Query('type') experienceType?: ExperienceType,
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
  ) {
    const result = await this.memoryService.getPendingExperiences({
      experienceType,
      page: page ? parseInt(page) : 1,
      pageSize: pageSize ? parseInt(pageSize) : 20,
    });
    return {
      success: true,
      data: result,
    };
  }

  /**
   * 审批经验
   */
  @Post('experience/:id/approve')
  async approveExperience(
    @Param('id') id: string,
    @Body() body: { adminId: string },
  ) {
    await this.memoryService.approveExperience(id, body.adminId);
    return {
      success: true,
      message: 'Experience approved',
    };
  }

  /**
   * 拒绝经验
   */
  @Post('experience/:id/reject')
  async rejectExperience(
    @Param('id') id: string,
    @Body() body: { adminId: string },
  ) {
    await this.memoryService.rejectExperience(id, body.adminId);
    return {
      success: true,
      message: 'Experience rejected',
    };
  }

  /**
   * 记录经验反馈
   */
  @Post('experience/:id/feedback')
  async recordExperienceFeedback(
    @Param('id') id: string,
    @Body() dto: MemoryFeedbackDto,
  ) {
    await this.memoryService.recordExperienceFeedback(id, dto.positive);
    return {
      success: true,
      message: 'Feedback recorded',
    };
  }

  /**
   * 获取经验统计
   */
  @Get('experience/statistics')
  async getExperienceStatistics() {
    const stats = await this.memoryService.getExperienceStatistics();
    return {
      success: true,
      data: stats,
    };
  }
}
