import { Body, Controller, Post, Query, UseGuards } from '@nestjs/common';
import { ZktecoService, type ZkAttendanceLog } from './zkteco.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';

@Controller('hr/zkteco')
@UseGuards(JwtAuthGuard)
export class ZktecoController {
  constructor(private service: ZktecoService) {}

  @Post('fetch')
  async fetch(
    @Query('ip') ip: string,
    @Query('port') port?: string,
  ): Promise<{ count: number; logs: ZkAttendanceLog[] } | { error: string }> {
    if (!ip) return { error: 'ip is required' };
    return this.service.fetchFromDevice(ip, port ? parseInt(port, 10) : 4370);
  }

  @Post('sync')
  async sync(
    @Body() body: { ip: string; port?: number },
    @Query('ip') ipQ?: string,
    @Query('port') portQ?: string,
  ) {
    const ip = body?.ip ?? ipQ;
    const port = body?.port ?? (portQ ? parseInt(portQ, 10) : 4370);
    if (!ip) return { error: 'ip is required' };
    return this.service.syncAttendance(ip, port);
  }

  @Post('info')
  async info(
    @Query('ip') ip: string,
    @Query('port') port?: string,
  ) {
    if (!ip) return { error: 'ip is required' };
    return this.service.getDeviceInfo(ip, port ? parseInt(port, 10) : 4370);
  }
}
