import { Controller, Get, Query, Param, UseGuards } from "@nestjs/common";
import { AuthGuard } from "../auth/guards/auth.guard";
import { WorkspaceGuard, PermissionGuard } from "../common/guards";
import { Workspace, RequirePermission, Permission } from "../common/decorators";
import { GraphService } from "./services";
import { GraphQueryDto, GraphFilterDto } from "./dto/graph-query.dto";

/**
 * Controller for knowledge graph endpoints
 * All endpoints require authentication and workspace context
 */
@Controller("knowledge/graph")
@UseGuards(AuthGuard, WorkspaceGuard, PermissionGuard)
export class KnowledgeGraphController {
  constructor(private readonly graphService: GraphService) {}

  /**
   * GET /api/knowledge/graph
   * Get full knowledge graph with optional filtering
   * Requires: Any workspace member
   */
  @Get()
  @RequirePermission(Permission.WORKSPACE_ANY)
  async getFullGraph(@Workspace() workspaceId: string, @Query() filters: GraphFilterDto) {
    return this.graphService.getFullGraph(workspaceId, filters);
  }

  /**
   * GET /api/knowledge/graph/stats
   * Get graph statistics including orphan detection
   * Requires: Any workspace member
   */
  @Get("stats")
  @RequirePermission(Permission.WORKSPACE_ANY)
  async getGraphStats(@Workspace() workspaceId: string) {
    return this.graphService.getGraphStats(workspaceId);
  }

  /**
   * GET /api/knowledge/graph/:slug
   * Get entry-centered graph view (subgraph)
   * Requires: Any workspace member
   */
  @Get(":slug")
  @RequirePermission(Permission.WORKSPACE_ANY)
  async getEntryGraph(
    @Workspace() workspaceId: string,
    @Param("slug") slug: string,
    @Query() query: GraphQueryDto
  ) {
    // Get entry by slug to find its ID
    return this.graphService.getEntryGraphBySlug(workspaceId, slug, query.depth ?? 1);
  }
}
