import {
  Controller,
  Get,
  Post,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
  Request,
} from '@nestjs/common';
import { CombinedAuthGuard } from '../auth/combined-auth.guard';
import { SearchHistoryService } from './search-history.service';
import { I18nService } from '../i18n/i18n.service';

@Controller('search-history')
@UseGuards(CombinedAuthGuard)
export class SearchHistoryController {
  constructor(
    private readonly searchHistoryService: SearchHistoryService,
    private readonly i18nService: I18nService,
  ) { }

  @Get()
  async findAll(
    @Request() req,
    @Query('page') page: string = '1',
    @Query('limit') limit: string = '20',
  ) {
    const pageNum = parseInt(page, 10) || 1;
    const limitNum = parseInt(limit, 10) || 20;

    return await this.searchHistoryService.findAll(req.user.id, req.user.tenantId, pageNum, limitNum);
  }

  @Get(':id')
  async findOne(@Param('id') id: string, @Request() req) {
    return await this.searchHistoryService.findOne(id, req.user.id, req.user.tenantId);
  }

  @Post()
  async create(
    @Body() body: { title: string; selectedGroups?: string[] },
    @Request() req,
  ) {
    const history = await this.searchHistoryService.create(
      req.user.id,
      req.user.tenantId,
      body.title,
      body.selectedGroups,
    );
    return { id: history.id };
  }

  @Delete(':id')
  async remove(@Param('id') id: string, @Request() req) {
    await this.searchHistoryService.remove(id, req.user.id, req.user.tenantId);
    return { message: this.i18nService.getMessage('searchHistoryDeleted') };
  }
}