package com.erp.approval.controller;

import com.erp.common.core.model.ApiResponse;
import com.erp.approval.dto.AuditLogQueryRequest;
import com.erp.common.core.model.PageResponse;
import com.erp.approval.entity.AuditLog;
import com.erp.approval.service.AuditLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 审核日志控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/audit-logs")
@RequiredArgsConstructor
public class AuditLogController {
    
    private final AuditLogService auditLogService;
    
    /**
     * 审计日志列表
     */
    @GetMapping
    public ApiResponse<PageResponse<AuditLog>> listLogs(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @RequestParam(required = false) Integer page,
            @RequestParam(required = false) Integer pageSize,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) String action,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String targetType,
            @RequestParam(required = false) Long targetId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        AuditLogQueryRequest request = AuditLogQueryRequest.builder()
                .page(page)
                .pageSize(pageSize)
                .module(module)
                .action(action)
                .userId(userId)
                .targetType(targetType)
                .targetId(targetId)
                .startDate(startDate)
                .endDate(endDate)
                .build();
        
        PageResponse<AuditLog> result = auditLogService.listLogs(tenantId, request);
        return ApiResponse.success(result);
    }
    
    /**
     * 审计日志详情
     */
    @GetMapping("/{id}")
    public ApiResponse<AuditLog> getLog(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @PathVariable Long id) {
        
        return auditLogService.getLogById(tenantId, id)
                .map(ApiResponse::success)
                .orElse(ApiResponse.error(404, "日志不存在"));
    }
    
    /**
     * 获取审计日志统计
     */
    @GetMapping("/stats")
    public ApiResponse<Map<String, Map<String, Long>>> getStats(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "0") Long tenantId,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Map<String, Map<String, Long>> result = auditLogService.getStats(tenantId, startDate, endDate);
        return ApiResponse.success(result);
    }
}
