package com.ga.common.system;

import com.ga.common.annotation.RequirePermission;
import com.ga.common.model.ApiResponse;
import com.ga.common.model.PageResponse;
import com.ga.common.model.SearchParam;
import com.github.pagehelper.PageHelper;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

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

@Tag(name = "시스템로그")
@RestController
@RequestMapping("/api/system/logs")
@RequiredArgsConstructor
public class SystemLogController {

    private final SystemLogMapper mapper;

    @GetMapping("/login")
    @RequirePermission(menu = "SYSTEM_LOG", perm = "READ")
    public ApiResponse<PageResponse<Map<String, Object>>> loginLogs(@ModelAttribute SearchParam param,
                                                                     @RequestParam(required = false) Long userId) {
        param.startPage();
        Map<String, Object> p = toMap(param);
        p.put("userId", userId);
        return ApiResponse.ok(PageResponse.of(mapper.selectLoginLogs(p)));
    }

    @GetMapping("/api")
    @RequirePermission(menu = "SYSTEM_LOG", perm = "READ")
    public ApiResponse<PageResponse<Map<String, Object>>> apiLogs(@ModelAttribute SearchParam param,
                                                                  @RequestParam(required = false) Long userId,
                                                                  @RequestParam(required = false) String url) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        Map<String, Object> p = toMap(param);
        p.put("userId", userId);
        p.put("url", url);
        return ApiResponse.ok(PageResponse.of(mapper.selectApiAccessLogs(p)));
    }

    @GetMapping("/data-change")
    @RequirePermission(menu = "SYSTEM_LOG", perm = "READ")
    public ApiResponse<PageResponse<Map<String, Object>>> dataChangeLogs(@ModelAttribute SearchParam param,
                                                                          @RequestParam(required = false) Long userId,
                                                                          @RequestParam(required = false) String tableName,
                                                                          @RequestParam(required = false) String recordId) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        Map<String, Object> p = toMap(param);
        p.put("userId", userId);
        p.put("tableName", tableName);
        p.put("recordId", recordId);
        return ApiResponse.ok(PageResponse.of(mapper.selectDataChangeLogs(p)));
    }

    private Map<String, Object> toMap(SearchParam p) {
        Map<String, Object> m = new HashMap<>();
        m.put("startDate", p.getStartDate());
        m.put("endDate",   p.getEndDate());
        return m;
    }
}
