import {
  Controller,
  Get,
  Put,
  Delete,
  Body,
  Param,
  UseGuards,
  HttpCode,
  HttpStatus,
} from "@nestjs/common";
import { AgentMemoryService } from "./agent-memory.service";
import { UpsertAgentMemoryDto } from "./dto";
import { AuthGuard } from "../auth/guards/auth.guard";
import { WorkspaceGuard, PermissionGuard } from "../common/guards";
import { Workspace, Permission, RequirePermission } from "../common/decorators";

/**
 * Controller for per-agent key/value memory endpoints.
 * All endpoints require authentication and workspace context.
 *
 * Guards are applied in order:
 * 1. AuthGuard - Verifies user authentication
 * 2. WorkspaceGuard - Validates workspace access
 * 3. PermissionGuard - Checks role-based permissions
 */
@Controller("agents/:agentId/memory")
@UseGuards(AuthGuard, WorkspaceGuard, PermissionGuard)
export class AgentMemoryController {
  constructor(private readonly agentMemoryService: AgentMemoryService) {}

  /**
   * PUT /api/agents/:agentId/memory/:key
   * Upsert a memory entry for an agent
   * Requires: MEMBER role or higher
   */
  @Put(":key")
  @RequirePermission(Permission.WORKSPACE_MEMBER)
  async upsert(
    @Param("agentId") agentId: string,
    @Param("key") key: string,
    @Body() dto: UpsertAgentMemoryDto,
    @Workspace() workspaceId: string
  ) {
    return this.agentMemoryService.upsert(workspaceId, agentId, key, dto);
  }

  /**
   * GET /api/agents/:agentId/memory
   * List all memory entries for an agent
   * Requires: Any workspace member (including GUEST)
   */
  @Get()
  @RequirePermission(Permission.WORKSPACE_ANY)
  async findAll(@Param("agentId") agentId: string, @Workspace() workspaceId: string) {
    return this.agentMemoryService.findAll(workspaceId, agentId);
  }

  /**
   * GET /api/agents/:agentId/memory/:key
   * Get a single memory entry by key
   * Requires: Any workspace member (including GUEST)
   */
  @Get(":key")
  @RequirePermission(Permission.WORKSPACE_ANY)
  async findOne(
    @Param("agentId") agentId: string,
    @Param("key") key: string,
    @Workspace() workspaceId: string
  ) {
    return this.agentMemoryService.findOne(workspaceId, agentId, key);
  }

  /**
   * DELETE /api/agents/:agentId/memory/:key
   * Remove a memory entry
   * Requires: MEMBER role or higher
   */
  @Delete(":key")
  @HttpCode(HttpStatus.OK)
  @RequirePermission(Permission.WORKSPACE_MEMBER)
  async remove(
    @Param("agentId") agentId: string,
    @Param("key") key: string,
    @Workspace() workspaceId: string
  ) {
    return this.agentMemoryService.remove(workspaceId, agentId, key);
  }
}
