// packages/backend/src/modules/netaclaw/controller/admin/memory.ts
import { Provide, Inject, Get, Post, Body, Query } from '@midwayjs/core';
import { CoolController, BaseController } from '@cool-midway/core';
import { MemoryAdminService } from '../../service/memory_admin.js';

@Provide()
@CoolController()
export class AdminNetaClawMemoryController extends BaseController {
  @Inject()
  memoryAdminService: MemoryAdminService;

  @Post('/page', { summary: '记忆分页查询' })
  async memoryPage(@Body() body: { agentName?: string; type?: string; keyWord?: string; page: number; size: number }) {
    const result = await this.memoryAdminService.memoryPage(body);
    return this.ok(result);
  }

  @Get('/info', { summary: '记忆详情' })
  async memoryInfo(@Query('agentName') agentName: string, @Query('id') id: number) {
    if (!agentName || !id) return this.fail('agentName 和 id 必填');
    const entry = await this.memoryAdminService.memoryInfo(agentName, id);
    if (!entry) return this.fail('记忆不存在');
    return this.ok(entry);
  }

  @Post('/add', { summary: '新增记忆' })
  async memoryAdd(@Body() body: { agentName: string; userId?: string; type: string; name: string; content: string; description?: string; metadata?: Record<string, unknown> }) {
    if (!body.agentName || !body.type || !body.name) return this.fail('agentName、type、name 必填');
    const entry = await this.memoryAdminService.memoryAdd(body);
    return this.ok(entry);
  }

  @Post('/update', { summary: '更新记忆（乐观锁）' })
  async memoryUpdate(@Body() body: { agentName: string; id: number; updatedAt?: string; name?: string; content?: string; description?: string; type?: string; metadata?: Record<string, unknown> }) {
    if (!body.agentName || !body.id) return this.fail('agentName 和 id 必填');
    try {
      const entry = await this.memoryAdminService.memoryUpdate(body);
      return this.ok(entry);
    } catch (e: unknown) {
      return this.fail(e instanceof Error ? e.message : '更新失败');
    }
  }

  @Post('/delete', { summary: '删除记忆' })
  async memoryDelete(@Body() body: { agentName: string; ids: number[] }) {
    if (!body.agentName || !body.ids?.length) return this.fail('agentName 和 ids 必填');
    await this.memoryAdminService.deleteMemories(body.agentName, body.ids);
    return this.ok();
  }

  @Get('/stats', { summary: '记忆统计' })
  async stats() {
    const result = await this.memoryAdminService.stats();
    return this.ok(result);
  }
}
