package gc.mda.kcg.admin;

import gc.mda.kcg.audit.AccessLog;
import gc.mda.kcg.audit.AccessLogRepository;
import gc.mda.kcg.audit.AuditLog;
import gc.mda.kcg.audit.AuditLogRepository;
import gc.mda.kcg.auth.LoginHistory;
import gc.mda.kcg.auth.LoginHistoryRepository;
import gc.mda.kcg.permission.annotation.RequirePermission;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 관리자 로그 조회 API.
 * - 감사 로그 (auth_audit_log)
 * - 접근 이력 (auth_access_log)
 * - 로그인 이력 (auth_login_hist)
 */
@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
public class AdminLogController {

    private final AuditLogRepository auditLogRepository;
    private final AccessLogRepository accessLogRepository;
    private final LoginHistoryRepository loginHistoryRepository;

    @GetMapping("/audit-logs")
    @RequirePermission(resource = "admin:audit-logs", operation = "READ")
    public Page<AuditLog> getAuditLogs(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "50") int size
    ) {
        return auditLogRepository.findAllByOrderByCreatedAtDesc(PageRequest.of(page, size));
    }

    @GetMapping("/access-logs")
    @RequirePermission(resource = "admin:access-logs", operation = "READ")
    public Page<AccessLog> getAccessLogs(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "50") int size
    ) {
        return accessLogRepository.findAllByOrderByCreatedAtDesc(PageRequest.of(page, size));
    }

    @GetMapping("/login-history")
    @RequirePermission(resource = "admin:login-history", operation = "READ")
    public Page<LoginHistory> getLoginHistory(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "50") int size
    ) {
        return loginHistoryRepository.findAllByOrderByLoginDtmDesc(PageRequest.of(page, size));
    }
}
