import { Body, Controller, Get, Post, Query } from '@nestjs/common';
import { CreateStructureDto } from './dto/create-structure.dto';
import { QueryStructure } from './dto/query-structure.dto';
import { Structure, StructureDocument } from './schemas/structure.schema';
import { StructuresService } from './structures.service';

@Controller('structures')
export class StructuresController {
  constructor(private readonly structureService: StructuresService) {}

  @Post()
  public async create(@Body() createStructureDto: CreateStructureDto) {
    await this.structureService.create(createStructureDto);
  }

  @Post('search')
  public async search(@Query() query: QueryStructure, @Body() body): Promise<Structure[]> {
    return this.structureService.search(query.query, body ? body.filters : null);
  }

  @Post(':id')
  public async update(@Param('id') id: number, @Body() body: CreateStructureDto) {
    return this.structureService.update(id, body);
  }

  @Get()
  public async findAll(): Promise<Structure[]> {
    return this.structureService.findAll();
  }

  @Get('count')
  public async countCategories(): Promise<Array<{ id: string; count: number }>> {
    const data = await Promise.all([
      this.structureService.countByStructureKey('proceduresAccompaniment'),

      this.structureService.countByStructureKey('accessRight'),
      this.structureService.countByStructureKey('baseSkills'),
      this.structureService.countByStructureKey('parentingHelp'),
      this.structureService.countByStructureKey('digitalCultureSecurity'),
      this.structureService.countByStructureKey('socialAndProfessional'),

      this.structureService.countByStructureKey('publicsAccompaniment'),
      this.structureService.countByStructureKey('labelsQualifications'),
      this.structureService.countByStructureKey('publics'),
      this.structureService.countByStructureKey('accessModality'),
      this.structureService.countByStructureKey('equipmentsAndServices'),
    ]);
    // Return a concat of all arrays
    return data.reduce((a, b) => [...a, ...b]);
  }

  @Get(':id')
  public async find(@Param('id') id: number) {
    return this.structureService.findOne(id);
  }
}