package com.eactive.eai.rms.ext.djb.webhook.controller;

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

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.eactive.eai.rms.data.entity.onl.djb.webhook.WebhookSendLog;
import com.eactive.eai.rms.ext.djb.webhook.dto.WebhookSendRequest;
import com.eactive.eai.rms.ext.djb.webhook.service.WebhookReceiveService;
import com.eactive.eai.rms.ext.djb.webhook.service.WebhookService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/webhook")
@RequiredArgsConstructor
public class WebhookSendController {

    private final WebhookService webhookService;
    private final WebhookReceiveService webhookReceiveService;
    
    private static final int KEY_BYTE_LENGTH = 32; // 256bit

    /* ------------------------------------------------------------------ */
    /*  발송                                                                 */
    /* ------------------------------------------------------------------ */

    @PostMapping("/send.json")
    public ResponseEntity<Map<String, Object>> sendWebhook(	
            @RequestBody WebhookSendRequest request) {

        webhookService.send(request);

        Map<String, Object> response = new HashMap<>();
//        response.put("logId", result.getId());
//        response.put("success", result.getSuccess());
//        response.put("statusCode", result.getStatusCode());

        return ResponseEntity.ok(response);
    }
    

    /* ------------------------------------------------------------------ */
    /*  수신                                                                 */
    /* ------------------------------------------------------------------ */

    /**
     * 웹훅 수신 엔드포인트
     *
     * 헤더 예시:
     *   X-Webhook-Signature : sha256={hmac값}
     *   X-Webhook-Event     : ORDER_CREATED
     *   X-Webhook-Timestamp : 1712345678901
     */
    @PostMapping("/receive")
    public ResponseEntity<Map<String, Object>> receiveWebhook(
            @RequestHeader(value = "X-Webhook-Signature",  required = false) String signature,
            @RequestHeader(value = "X-Webhook-Event",      required = false) String eventType,
            @RequestHeader(value = "X-Webhook-Timestamp",  required = false) String timestamp,
            @RequestBody String rawPayload) {

        log.info("[Webhook] 수신 - eventType: {}, timestamp: {}", eventType, timestamp);

        // 1. 필수 헤더 누락 체크
        if (signature == null || eventType == null || timestamp == null) {
            log.warn("[Webhook] 수신 거부 - 필수 헤더 누락");
            return ResponseEntity
                    .status(HttpStatus.BAD_REQUEST)
                    .body(errorResponse("필수 헤더가 누락되었습니다."));
        }

        // 2. 서명 검증
        boolean isValid = webhookReceiveService.verifySignature(rawPayload, signature);
        if (!isValid) {
            log.warn("[Webhook] 수신 거부 - 서명 불일치 / eventType: {}", eventType);
            return ResponseEntity
                    .status(HttpStatus.UNAUTHORIZED)
                    .body(errorResponse("서명 검증에 실패하였습니다."));
        }

        // 3. 타임스탬프 유효성 검증 (5분 이내 요청만 허용)
        boolean isTimestampValid = webhookReceiveService.verifyTimestamp(timestamp);
        if (!isTimestampValid) {
            log.warn("[Webhook] 수신 거부 - 타임스탬프 만료 / eventType: {}", eventType);
            return ResponseEntity
                    .status(HttpStatus.UNAUTHORIZED)
                    .body(errorResponse("요청이 만료되었습니다."));
        }

        // 4. 이벤트 처리
        try {
            webhookReceiveService.process(eventType, rawPayload);
        } catch (Exception e) {
            log.error("[Webhook] 이벤트 처리 실패 - eventType: {}, error: {}", eventType, e.getMessage(), e);
            return ResponseEntity
                    .status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse("이벤트 처리 중 오류가 발생하였습니다."));
        }

        // 5. 정상 응답
        Map<String, Object> response = new HashMap<>();
        response.put("result", "OK");
        response.put("eventType", eventType);

        return ResponseEntity.ok(response);
    }

    /* ------------------------------------------------------------------ */
    /*  공통                                                                 */
    /* ------------------------------------------------------------------ */

    private Map<String, Object> errorResponse(String message) {
        Map<String, Object> error = new HashMap<>();
        error.put("result", "ERROR");
        error.put("message", message);
        return error;
    }
}