package com.erp.controller;

import com.erp.dto.ApiResponse;
import com.erp.service.AuditLogService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/audit-logs")
@RequiredArgsConstructor
@Slf4j
public class AuditLogController {

    private final AuditLogService auditLogService;

    /**
     * GET /api/audit-logs
     * 감사 로그 목록 조회 (페이지네이션 + 필터)
     * 응답: { success, data, total, page, limit }
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAuditLogs(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("role") String role,
            @RequestParam Map<String, Object> queryParams) {

        boolean isSuperAdmin = isSuperAdmin(role);

        // SUPER_ADMIN: 쿼리 파라미터 companyCode 사용(없으면 전체); 일반: JWT companyCode 강제 적용
        String filterCompany = isSuperAdmin
                ? (String) queryParams.get("company_code")
                : companyCode;

        Map<String, Object> filters = new HashMap<>(queryParams);
        filters.put("filter_company", filterCompany);

        int page = toInt(queryParams.get("page"), 1);
        int limit = toInt(queryParams.get("limit"), 50);
        filters.put("page", page);
        filters.put("limit", limit);

        Map<String, Object> result = auditLogService.queryLogs(filters, isSuperAdmin);

        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", result.get("data"));
        response.put("total", result.get("total"));
        response.put("page", page);
        response.put("limit", limit);
        return ResponseEntity.ok(response);
    }

    /**
     * GET /api/audit-logs/stats
     * 감사 로그 통계 (일별 / 리소스타입 / 액션 / 상위사용자)
     */
    @GetMapping("/stats")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getAuditLogStats(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("role") String role,
            @RequestParam(value = "company_code", required = false) String queryCompanyCode,
            @RequestParam(required = false, defaultValue = "30") int days) {

        boolean isSuperAdmin = isSuperAdmin(role);
        String targetCompany = isSuperAdmin ? queryCompanyCode : companyCode;

        Map<String, Object> stats = auditLogService.getStats(targetCompany, days);
        return ResponseEntity.ok(ApiResponse.success(stats));
    }

    /**
     * GET /api/audit-logs/users
     * 감사 로그 사용자 목록 (로그 건수 포함)
     */
    @GetMapping("/users")
    public ResponseEntity<ApiResponse<List<Map<String, Object>>>> getAuditLogUsers(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("role") String role,
            @RequestParam(value = "company_code", required = false) String queryCompanyCode) {

        boolean isSuperAdmin = isSuperAdmin(role);
        String targetCompany = isSuperAdmin ? queryCompanyCode : companyCode;

        List<Map<String, Object>> users = auditLogService.getAuditLogUsers(targetCompany, isSuperAdmin);
        return ResponseEntity.ok(ApiResponse.success(users));
    }

    /**
     * POST /api/audit-logs
     * 감사 로그 직접 기록 (프론트엔드 오케스트레이션용)
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Void>> createAuditLog(
            @RequestAttribute("company_code") String companyCode,
            @RequestAttribute("user_id") String userId,
            @RequestAttribute("role") String role,
            @RequestBody Map<String, Object> body,
            HttpServletRequest request) {

        String action = (String) body.get("action");
        String resourceType = (String) body.get("resource_type");

        if (action == null || action.isBlank() || resourceType == null || resourceType.isBlank()) {
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("action, resourceType은 필수입니다."));
        }

        Map<String, Object> params = new HashMap<>(body);
        params.put("company_code", companyCode);
        params.put("user_id", userId);
        // userName: request attribute(JWT) → body fallback
        if (!params.containsKey("user_name")) {
            Object userName = request.getAttribute("user_name");
            if (userName != null) {
                params.put("user_name", userName);
            }
        }
        params.put("ip_address", resolveClientIp(request));
        params.put("request_path", request.getRequestURI());

        auditLogService.insertAuditLog(params);
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    // ── 내부 유틸 ────────────────────────────────────────────────────────────

    private boolean isSuperAdmin(String role) {
        return "SUPER_ADMIN".equals(role);
    }

    private int toInt(Object value, int defaultVal) {
        if (value == null) return defaultVal;
        try {
            return Integer.parseInt(value.toString());
        } catch (NumberFormatException e) {
            return defaultVal;
        }
    }

    private String resolveClientIp(HttpServletRequest request) {
        String forwarded = request.getHeader("X-Forwarded-For");
        if (forwarded != null && !forwarded.isBlank()) {
            return forwarded.split(",")[0].trim();
        }
        String realIp = request.getHeader("X-Real-IP");
        if (realIp != null && !realIp.isBlank()) return realIp;
        return request.getRemoteAddr();
    }
}
