package com.zioinfo.esn.controller;

import com.zioinfo.esn.admin.AuditService;
import com.zioinfo.esn.common.ApiResponse;
import com.zioinfo.esn.domain.PosCvtVo;
import com.zioinfo.esn.service.PosCvtService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/pos-cvt")
@RequiredArgsConstructor
public class PosCvtController {
    private final PosCvtService service;
    private final AuditService audit;

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

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

    @PutMapping("/{id}/process")
    public ApiResponse<Integer> process(@PathVariable Long id) {
        PosCvtVo pos = service.get(id);
        int queued = service.process(id);
        // ESL 가격 변경 전파 — 추적 가치 높음 (가격은 영업정보이나 민감개인정보 아님)
        String detail = pos == null ? ("queued=" + queued)
                : ("product=" + pos.getProductCode() + ", price=" + pos.getPrice() + ", queued=" + queued);
        audit.log(pos != null ? pos.getTenantCode() : null, "POS_PRICE_CHANGE", "POS_CVT",
                String.valueOf(id), detail, true);
        return ApiResponse.ok("처리 완료 (태그 큐 " + queued + "건)", queued);
    }

    @PutMapping("/{id}/ignore")
    public ApiResponse<Void> ignore(@PathVariable Long id) {
        service.ignore(id);
        return ApiResponse.ok("무시 처리 완료", null);
    }

    @PutMapping("/{id}/error")
    public ApiResponse<Void> error(@PathVariable Long id, @RequestBody Map<String, String> body) {
        service.markError(id, body.getOrDefault("message", "처리 오류"));
        return ApiResponse.ok("오류 처리 완료", null);
    }
}
