package com.zioinfo.signage.controller;

import com.zioinfo.signage.common.ApiResponse;
import com.zioinfo.signage.domain.UpdateQueueVo;
import com.zioinfo.signage.service.UpdateQueueService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

/**
 * e-paper 태그 가격 업데이트 전파 큐
 * Gateway가 이 API를 주기적으로 폴링 → 태그에 RF 전송 → confirm 호출
 *
 * Gateway 연동 흐름:
 *   GET /api/update-queue/poll?tenantCode=EMART&limit=50  → PENDING 목록 수신
 *   PUT /api/update-queue/{id}/sent                       → RF 전송 완료
 *   PUT /api/update-queue/confirm?deviceId=ESL-001        → 태그 ACK 수신
 */
@RestController
@RequestMapping("/api/update-queue")
@RequiredArgsConstructor
public class UpdateQueueController {
    private final UpdateQueueService service;

    @GetMapping
    public ApiResponse<List<UpdateQueueVo>> list(
            @RequestParam(required = false) String tenantCode,
            @RequestParam(required = false) Long storeId,
            @RequestParam(required = false) String status) {
        return ApiResponse.ok(service.list(tenantCode, storeId, status));
    }

    @GetMapping("/{id}")
    public ApiResponse<UpdateQueueVo> get(@PathVariable Long id) {
        return ApiResponse.ok(service.get(id));
    }

    /** Gateway 폴링 엔드포인트: PENDING → SENDING 전환 후 반환 */
    @GetMapping("/poll")
    public ApiResponse<List<UpdateQueueVo>> poll(
            @RequestParam(required = false) String tenantCode,
            @RequestParam(defaultValue = "50") int limit) {
        return ApiResponse.ok(service.pollPending(tenantCode, limit));
    }

    /** Gateway가 RF 전송 완료 후 호출 */
    @PutMapping("/{id}/sent")
    public ApiResponse<Void> sent(@PathVariable Long id) {
        service.markSent(id);
        return ApiResponse.ok("전송 완료", null);
    }

    /** 태그로부터 확인 응답 수신 (device_id 기반 일괄 확인) */
    @PutMapping("/confirm")
    public ApiResponse<Void> confirm(@RequestParam String deviceId) {
        service.confirm(deviceId);
        return ApiResponse.ok("확인 완료", null);
    }

    /** 전송 실패 처리 */
    @PutMapping("/{id}/failed")
    public ApiResponse<Void> failed(@PathVariable Long id,
                                    @RequestBody Map<String, String> body) {
        service.markFailed(id, body.getOrDefault("message", "전송 실패"));
        return ApiResponse.ok("실패 처리 완료", null);
    }

    /** 큐 항목 취소 */
    @PutMapping("/{id}/cancel")
    public ApiResponse<Void> cancel(@PathVariable Long id) {
        service.cancel(id);
        return ApiResponse.ok("취소 완료", null);
    }
}
