import { Controller, Get, Query } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiQuery } from '@nestjs/swagger';
import { DashboardService } from '../../application/services/dashboard.service';

@ApiTags('Audit')
@ApiBearerAuth()
@Controller('audit')
export class AuditController {
  constructor(private readonly dashboardService: DashboardService) {}

  @Get()
  @ApiOperation({ summary: '获取审计日志' })
  @ApiQuery({ name: 'adminId', required: false })
  @ApiQuery({ name: 'action', required: false })
  @ApiQuery({ name: 'resource', required: false })
  @ApiQuery({ name: 'keyword', required: false })
  @ApiQuery({ name: 'page', required: false, type: Number })
  @ApiQuery({ name: 'pageSize', required: false, type: Number })
  async getAuditLogs(
    @Query('adminId') adminId?: string,
    @Query('action') action?: string,
    @Query('resource') resource?: string,
    @Query('keyword') keyword?: string,
    @Query('page') page?: number,
    @Query('pageSize') pageSize?: number,
  ) {
    const result = await this.dashboardService.getAuditLogs({
      adminId,
      action,
      resource,
      page: page ?? 1,
      pageSize: pageSize ?? 20,
    });

    // 转换为前端期望的格式
    return {
      items: result.data.map((log: any) => ({
        id: log.id,
        adminId: log.adminId,
        adminUsername: log.admin?.username || 'unknown',
        action: log.action,
        resource: log.resource,
        resourceId: log.resourceId,
        details: log.newValue ? JSON.stringify(log.newValue) : null,
        ipAddress: log.ipAddress || '-',
        createdAt: log.createdAt,
      })),
      total: result.total,
      page: result.pagination.page,
      pageSize: result.pagination.pageSize,
      totalPages: result.pagination.totalPages,
    };
  }
}
