package com.lesingle.edu.controller.school;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lesingle.edu.common.annotation.RequireRole;
import com.lesingle.edu.common.enums.LogModule;
import com.lesingle.edu.common.enums.UserRole;
import com.lesingle.edu.common.response.PageResult;
import com.lesingle.edu.common.response.Result;
import com.lesingle.edu.common.security.SecurityUtils;
import com.lesingle.edu.dto.response.OperationLogResponse;
import com.lesingle.edu.entity.OperationLog;
import com.lesingle.edu.service.OperationLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 学校端 - 操作日志
 */
@Tag(name = "学校端 - 操作日志", description = "School Operation Log APIs")
@RestController
@RequestMapping("/api/v1/school/operation-logs")
@RequiredArgsConstructor
@RequireRole(UserRole.SCHOOL)
public class SchoolOperationLogController {

    private final OperationLogService operationLogService;

    @GetMapping
    @Operation(summary = "获取日志列表")
    public Result<PageResult<OperationLogResponse>> getLogList(
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String module,
            @RequestParam(required = false) String action) {

        // 获取当前租户 ID
        Long tenantId = SecurityUtils.getCurrentTenantId();

        // 调用 Service 层查询
        Page<OperationLog> page = operationLogService.getLogPage(
                tenantId, pageNum, pageSize, module, action
        );

        // Entity 转为 Response
        List<OperationLogResponse> responseList = page.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());

        PageResult<OperationLogResponse> result = new PageResult<>();
        result.setList(responseList);
        result.setTotal(page.getTotal());
        result.setPageNum(page.getCurrent());
        result.setPageSize(page.getSize());
        result.setPages((page.getTotal() + pageSize - 1) / pageSize);

        return Result.success(result);
    }

    @GetMapping("/stats")
    @Operation(summary = "获取日志统计")
    public Result<Map<String, Object>> getLogStats() {
        // 获取当前租户 ID
        Long tenantId = SecurityUtils.getCurrentTenantId();

        // 调用 Service 层查询
        Map<String, Object> stats = operationLogService.getLogStats(tenantId);
        return Result.success(stats);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取日志详情")
    public Result<OperationLogResponse> getLogDetail(@PathVariable Long id) {
        // 通过服务层获取日志（包含租户验证）
        OperationLog log = operationLogService.getLogByIdWithTenantCheck(id);
        return Result.success(convertToResponse(log));
    }

    @GetMapping("/modules")
    @Operation(summary = "获取可用模块列表")
    public Result<List<String>> getAvailableModules() {
        // 从枚举获取所有模块描述
        List<String> modules = Arrays.stream(LogModule.values())
            .map(LogModule::toString)
            .collect(Collectors.toList());
        return Result.success(modules);
    }

    /**
     * Entity 转 Response
     */
    private OperationLogResponse convertToResponse(OperationLog log) {
        return OperationLogResponse.builder()
                .id(log.getId())
                .tenantId(log.getTenantId())
                .userId(log.getUserId())
                .userRole(log.getUserRole())
                .action(log.getAction())
                .module(log.getModule())
                .targetType(log.getTargetType())
                .targetId(log.getTargetId())
                .details(log.getDetails())
                .ipAddress(log.getIpAddress())
                .userAgent(log.getUserAgent())
                .requestParams(log.getRequestParams())
                .requestUri(log.getRequestUri())
                .createBy(log.getCreateBy())
                .createdAt(log.getCreatedAt())
                .build();
    }
}
