import { Body, Controller, Delete, Get, Param, Post, Query, UseGuards } from "@nestjs/common";
import { AuthGuard } from "../auth/guards/auth.guard";
import { WorkspaceGuard, PermissionGuard } from "../common/guards";
import { Workspace, Permission, RequirePermission } from "../common/decorators";
import { CreateFindingDto, QueryFindingsDto, SearchFindingsDto } from "./dto";
import {
  FindingsService,
  FindingsSearchResponse,
  PaginatedFindingsResponse,
} from "./findings.service";

/**
 * Controller for findings endpoints
 * All endpoints require authentication and workspace context
 */
@Controller("findings")
@UseGuards(AuthGuard, WorkspaceGuard, PermissionGuard)
export class FindingsController {
  constructor(private readonly findingsService: FindingsService) {}

  /**
   * POST /api/findings
   * Create a new finding and embed its summary
   * Requires: MEMBER role or higher
   */
  @Post()
  @RequirePermission(Permission.WORKSPACE_MEMBER)
  async create(@Body() createFindingDto: CreateFindingDto, @Workspace() workspaceId: string) {
    return this.findingsService.create(workspaceId, createFindingDto);
  }

  /**
   * GET /api/findings
   * Get paginated findings with optional filters
   * Requires: Any workspace member
   */
  @Get()
  @RequirePermission(Permission.WORKSPACE_ANY)
  async findAll(
    @Query() query: QueryFindingsDto,
    @Workspace() workspaceId: string
  ): Promise<PaginatedFindingsResponse> {
    return this.findingsService.findAll(workspaceId, query);
  }

  /**
   * GET /api/findings/:id
   * Get a single finding by ID
   * Requires: Any workspace member
   */
  @Get(":id")
  @RequirePermission(Permission.WORKSPACE_ANY)
  async findOne(@Param("id") id: string, @Workspace() workspaceId: string) {
    return this.findingsService.findOne(id, workspaceId);
  }

  /**
   * POST /api/findings/search
   * Semantic search findings by vector similarity
   * Requires: Any workspace member
   */
  @Post("search")
  @RequirePermission(Permission.WORKSPACE_ANY)
  async search(
    @Body() searchDto: SearchFindingsDto,
    @Workspace() workspaceId: string
  ): Promise<FindingsSearchResponse> {
    return this.findingsService.search(workspaceId, searchDto);
  }

  /**
   * DELETE /api/findings/:id
   * Delete a finding
   * Requires: ADMIN role or higher
   */
  @Delete(":id")
  @RequirePermission(Permission.WORKSPACE_ADMIN)
  async remove(@Param("id") id: string, @Workspace() workspaceId: string) {
    return this.findingsService.remove(id, workspaceId);
  }
}
