import {
  Controller,
  Get,
  HttpCode,
  HttpStatus,
  Query,
  Req,
  UnauthorizedException,
  UseGuards,
} from '@nestjs/common';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiResponse,
  ApiTags,
} from '@nestjs/swagger';
import type { Request } from 'express';

import { JwtAuthGuard } from '@/modules/auth/jwt-auth.guard';

import { QuerySearchDto } from './dto/query-search.dto';
import { SearchService } from './search.service';

type AuthenticatedRequest = Request & {
  user?: { id?: number };
};

// No single permission covers every group, so the route only needs a signed-in
// user: the service checks each group against the caller's own permissions.
@ApiTags('search')
@ApiBearerAuth('access-token')
@UseGuards(JwtAuthGuard)
@Controller('search')
export class SearchController {
  constructor(private readonly searchService: SearchService) {}

  @Get()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Search everything the caller is allowed to read' })
  @ApiResponse({ status: 200, description: 'Hits grouped by kind of record.' })
  search(@Req() request: AuthenticatedRequest, @Query() query: QuerySearchDto) {
    const userId = Number(request.user?.id);

    if (!Number.isInteger(userId) || userId <= 0) {
      throw new UnauthorizedException('Invalid authenticated user.');
    }

    return this.searchService.search(userId, query.q ?? '', query.limit);
  }
}
