package com.zioinfo.kintex.module.m5;

import com.zioinfo.kintex.common.ApiResponse;
import com.zioinfo.kintex.common.error.ApiException;
import com.zioinfo.kintex.common.error.ErrorCode;
import com.zioinfo.kintex.module.m5.dto.RenderJobDto;
import com.zioinfo.kintex.module.m5.dto.WorkerCallbackRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * 나노바나나 Python 워커 → 백엔드 완료 콜백(내부 전용). JWT 사용자가 아니라 워커이므로
 * 공유 시크릿 헤더(X-Worker-Token, env RENDER_WORKER_TOKEN)로 인증한다. 시크릿은 env에서만 로드.
 */
@RestController
@RequestMapping("/api/internal/render")
public class RenderWorkerCallbackController {

    private final RenderJobService service;
    private final String workerToken;

    public RenderWorkerCallbackController(RenderJobService service,
                                          @Value("${RENDER_WORKER_TOKEN:}") String workerToken) {
        this.service = service;
        this.workerToken = workerToken;
    }

    /** POST /callback — 워커 완료/실패 통지 → 상태 갱신 + WebSocket 푸시. */
    @PostMapping("/callback")
    public ApiResponse<RenderJobDto> callback(@RequestHeader(value = "X-Worker-Token", required = false) String token,
                                              @Valid @RequestBody WorkerCallbackRequest request) {
        if (workerToken == null || workerToken.isBlank() || !workerToken.equals(token)) {
            throw new ApiException(ErrorCode.UNAUTHORIZED, "워커 인증에 실패했습니다.");
        }
        return ApiResponse.ok(service.handleWorkerCallback(request));
    }
}
