import { Controller, Get, Post, Query, Body, HttpException, HttpStatus } from '@nestjs/common';
import { HcmService } from './hcm.service';

@Controller('api/hcm')
export class HcmController {
  constructor(private readonly hcmService: HcmService) {}

  // GET /api/hcm/folha?competencia=01/04/2026&tipo=1
  @Get('folha')
  async getFolha(
    @Query('competencia') competencia: string,
    @Query('tipo') tipo = '1',
  ) {
    if (!competencia) {
      throw new HttpException('Parâmetro competencia obrigatório (ex: 01/04/2026)', HttpStatus.BAD_REQUEST);
    }
    try {
      return await this.hcmService.getContraCheque(competencia, tipo);
    } catch (err) {
      throw new HttpException(
        err?.response?.data || err.message || 'Erro na API HCM',
        HttpStatus.BAD_GATEWAY,
      );
    }
  }

  // GET /api/hcm/colaboradores?dtInicio=01/01/2024&dtFim=30/11/2099&estrutura=7
  @Get('colaboradores')
  async getColaboradores(
    @Query('dtInicio') dtInicio = '01/01/2024',
    @Query('dtFim') dtFim = '30/11/2099',
    @Query('estrutura') estrutura = '7',
  ) {
    try {
      return await this.hcmService.getColaboradores(dtInicio, dtFim, parseInt(estrutura));
    } catch (err) {
      throw new HttpException(
        err?.response?.data || err.message || 'Erro na API HCM',
        HttpStatus.BAD_GATEWAY,
      );
    }
  }

  // GET /api/hcm/status — health check
  @Get('status')
  async getStatus() {
    try {
      const token = await this.hcmService.getToken();
      return { ok: true, tokenOk: !!token };
    } catch (err) {
      return { ok: false, error: err.message };
    }
  }
}
