import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put, Query, Request, UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RequirePermission } from '../auth/decorators/permission.decorator';
import { OperationLogsService } from '../operation-logs/operation-logs.service';
import { extractRequestInfo } from '../common/request-utils';
import { AttendanceDevicesService } from './attendance-devices.service';
import { CreateAttendanceDeviceDto, UpdateAttendanceDeviceDto } from './dto/attendance-device.dto';
import { AttendanceDeviceStatus } from '../entities';

@UseGuards(JwtAuthGuard)
@Controller('attendance-devices')
export class AttendanceDevicesController {
  constructor(
    private readonly service: AttendanceDevicesService,
    private readonly logService: OperationLogsService,
  ) {}

  @Get()
  @RequirePermission('classroom:view')
  findAll(
    @Query('classroomId') classroomId?: string,
    @Query('status') status?: AttendanceDeviceStatus | 'active' | 'disabled',
  ) {
    return this.service.findAll({
      classroomId: classroomId ? Number(classroomId) : undefined,
      status,
    });
  }

  @Post()
  @RequirePermission('classroom:edit')
  async create(@Body() dto: CreateAttendanceDeviceDto, @Request() req: any) {
    const { ipAddress, userAgent } = extractRequestInfo(req);
    const result = await this.service.create(dto);
    await this.logService.log({
      userId: req.user?.id,
      username: req.user?.username,
      module: '考勤机',
      action: '新增考勤机绑定',
      targetId: result.id,
      targetType: 'attendanceDevice',
      detail: `${result.deviceSn} -> ${result.classroom?.name || result.classroomId}`,
      ipAddress,
      userAgent,
    });
    return result;
  }

  @Put(':id')
  @RequirePermission('classroom:edit')
  async update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateAttendanceDeviceDto, @Request() req: any) {
    const { ipAddress, userAgent } = extractRequestInfo(req);
    const result = await this.service.update(id, dto);
    await this.logService.log({
      userId: req.user?.id,
      username: req.user?.username,
      module: '考勤机',
      action: '编辑考勤机绑定',
      targetId: id,
      targetType: 'attendanceDevice',
      detail: JSON.stringify(dto),
      ipAddress,
      userAgent,
    });
    return result;
  }

  @Delete(':id')
  @RequirePermission('classroom:edit')
  async remove(@Param('id', ParseIntPipe) id: number, @Request() req: any) {
    const { ipAddress, userAgent } = extractRequestInfo(req);
    const result = await this.service.remove(id);
    await this.logService.log({
      userId: req.user?.id,
      username: req.user?.username,
      module: '考勤机',
      action: '停用考勤机绑定',
      targetId: id,
      targetType: 'attendanceDevice',
      ipAddress,
      userAgent,
    });
    return result;
  }
}
