package com.erp.systemtool.controller;

import com.erp.systemtool.entity.OperationLog;
import com.erp.systemtool.service.OperationLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Operation Log Controller
 * 
 * Provides REST API for operation log management.
 * Migrations from PHP OperationLogController.
 */
@RestController
@RequestMapping("/api/system/logs")
@RequiredArgsConstructor
public class OperationLogController {

    private final OperationLogService logService;

    /**
     * Query operation logs with filters
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> queryLogs(
            @RequestParam Map<String, Object> params,
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "1") Integer tenantId) {
        
        Map<String, Object> result = logService.queryLogs(tenantId, params);
        result.put("code", 200);
        result.put("message", "success");
        return ResponseEntity.ok(result);
    }

    /**
     * Get log detail by ID
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getLogById(
            @PathVariable Long id,
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "1") Integer tenantId) {
        
        return logService.getLogById(id, tenantId)
            .map(log -> ResponseEntity.ok(Map.<String, Object>of(
                "code", 200,
                "data", log,
                "message", "success"
            )))
            .orElse(ResponseEntity.status(404).body(Map.of(
                "code", 404,
                "message", "日志不存在"
            )));
    }

    /**
     * Delete a single log
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteLog(
            @PathVariable Long id,
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "1") Integer tenantId) {
        
        boolean deleted = logService.deleteLog(id, tenantId);
        
        if (deleted) {
            return ResponseEntity.ok(Map.of(
                "code", 200,
                "message", "操作日志删除成功"
            ));
        } else {
            return ResponseEntity.status(404).body(Map.of(
                "code", 404,
                "message", "日志不存在"
            ));
        }
    }

    /**
     * Batch delete logs
     */
    @PostMapping("/batch-delete")
    public ResponseEntity<Map<String, Object>> batchDelete(
            @RequestBody Map<String, Object> request,
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "1") Integer tenantId) {
        
        @SuppressWarnings("unchecked")
        List<Long> logIds = (List<Long>) request.get("log_ids");
        
        if (logIds == null || logIds.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of(
                "code", 400,
                "message", "log_ids is required"
            ));
        }

        Map<String, Object> result = logService.batchDelete(logIds, tenantId);
        int successCount = (int) result.get("success_count");
        
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("data", result);
        response.put("message", String.format("批量删除成功，成功 %d 个", successCount));
        
        return ResponseEntity.ok(response);
    }

    /**
     * Clear old logs
     */
    @DeleteMapping("/clear")
    public ResponseEntity<Map<String, Object>> clearLogs(
            @RequestParam(required = false) Integer days,
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "1") Integer tenantId) {
        
        long deletedCount = logService.clearOldLogs(tenantId, days);
        
        return ResponseEntity.ok(Map.of(
            "code", 200,
            "data", Map.of("deleted_count", deletedCount),
            "message", String.format("成功清空 %d 条操作日志", deletedCount)
        ));
    }

    /**
     * Get operation statistics
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false, defaultValue = "day") String groupBy,
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "1") Integer tenantId) {
        
        Map<String, Object> stats = logService.getStatistics(tenantId, startDate, endDate, groupBy);
        
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("data", stats);
        response.put("message", "success");
        
        return ResponseEntity.ok(response);
    }

    /**
     * Get distinct modules
     */
    @GetMapping("/modules")
    public ResponseEntity<Map<String, Object>> getModules(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "1") Integer tenantId) {
        
        List<String> modules = logService.getModules(tenantId);
        
        return ResponseEntity.ok(Map.of(
            "code", 200,
            "data", modules,
            "message", "success"
        ));
    }

    /**
     * Get distinct actions
     */
    @GetMapping("/actions")
    public ResponseEntity<Map<String, Object>> getActions(
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "1") Integer tenantId) {
        
        List<String> actions = logService.getActions(tenantId);
        
        return ResponseEntity.ok(Map.of(
            "code", 200,
            "data", actions,
            "message", "success"
        ));
    }

    /**
     * Export logs (placeholder - actual export handled by export service)
     */
    @GetMapping("/export")
    public ResponseEntity<Map<String, Object>> exportLogs(
            @RequestParam(required = false) String format,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "1") Integer tenantId) {
        
        // Return export metadata - actual file generation would be async
        Map<String, Object> params = new HashMap<>();
        params.put("tenantId", tenantId);
        if (startDate != null) params.put("startDate", startDate);
        if (endDate != null) params.put("endDate", endDate);
        
        return ResponseEntity.ok(Map.of(
            "code", 200,
            "data", Map.of(
                "format", format != null ? format : "csv",
                "download_url", null,
                "message", "Export request accepted"
            ),
            "message", "导出请求已接收"
        ));
    }

    /**
     * Create operation log (internal use)
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> createLog(
            @RequestBody OperationLog operationLog,
            @RequestHeader(value = "X-Tenant-Id", defaultValue = "1") Integer tenantId) {
        
        operationLog.setTenantId(tenantId);
        OperationLog created = logService.createLog(operationLog);
        
        return ResponseEntity.ok(Map.of(
            "code", 200,
            "data", created,
            "message", "success"
        ));
    }
}
