package br.gov.sigefp.admin.api;

import br.gov.sigefp.admin.api.dto.AuditLogDTO;
import br.gov.sigefp.admin.service.AuditLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.util.UUID;

/**
 * Controller REST para consulta de logs de auditoria (somente leitura).
 */
@RestController
@RequestMapping("/api/admin/audit-logs")
@RequiredArgsConstructor
public class AuditLogController {

    private final AuditLogService auditLogService;

    @GetMapping
    public ResponseEntity<Page<AuditLogDTO>> findLogs(
            @RequestParam(required = false) UUID userId,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Instant endDate,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false, defaultValue = "DESC") String sortDirection) {
        
        Sort sort = sortBy != null 
            ? Sort.by(Sort.Direction.fromString(sortDirection), sortBy)
            : Sort.by(Sort.Direction.DESC, "createdAt");
        
        Pageable pageable = PageRequest.of(page, size, sort);
        Page<AuditLogDTO> result = auditLogService.findLogs(userId, module, startDate, endDate, pageable);
        return ResponseEntity.ok(result);
    }
}

