import {
  Controller, Get, Param,
  Query, UseGuards, Res
} from '@nestjs/common';
import type { Response } from 'express';
import { AuditService } from './audit.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles, Role } from '../common/decorators/roles.decorator';

@Controller('audit')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles(Role.DIRECTOR, Role.ADMIN)
export class AuditController {
  constructor(private readonly auditService: AuditService) {}

  // Liste des logs avec filtres
  @Get()
  findAll(
    @Query('user_id')     userId?: string,
    @Query('entity_type') entityType?: string,
    @Query('action')      action?: string,
    @Query('start_date')  startDate?: string,
    @Query('end_date')    endDate?: string,
    @Query('page')        page?: string,
    @Query('limit')       limit?: string,
  ) {
    return this.auditService.findAll({
      user_id:     userId     ? +userId : undefined,
      entity_type: entityType,
      action,
      start_date:  startDate,
      end_date:    endDate,
      page:        page  ? +page  : 1,
      limit:       limit ? +limit : 20,
    });
  }

  // Stats résumé
  @Get('stats')
  getStats() {
    return this.auditService.getStats();
  }

  // Actions disponibles
  @Get('actions')
  getActions() {
    return this.auditService.getAvailableActions();
  }

  // Types d'entités disponibles
  @Get('entity-types')
  getEntityTypes() {
    return this.auditService.getAvailableEntityTypes();
  }

  @Get('export/csv')
  async exportCSV(@Query() filters, @Res() res: Response) {
    const csv = await this.auditService.exportCSV(filters);
    res.set({ 'Content-Type': 'text/csv; charset=utf-8',
      'Content-Disposition': `attachment; filename="audit-${Date.now()}.csv"` });
    res.end(csv);
  }

  // Logs d'une entité spécifique
  @Get(':entityType/:entityId')
  findByEntity(
    @Param('entityType') entityType: string,
    @Param('entityId')   entityId: string,
  ) {
    return this.auditService.findByEntity(entityType, +entityId);
  }

  // Détail d'un log
  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.auditService.findOne(+id);
  }
}