package com.zioinfo.signage.controller;

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

@RestController
@RequestMapping("/api/sign-deploys")
@RequiredArgsConstructor
public class SignDeployController {
    private final SignDeployService service;

    /**
     * 매장(간판) 단말 30초 폴링 — {header:{token}, body:{type,sub_type,code,path,md5,file_name,file_size}}.
     * 사업계획서 슬라이드20 REST 계약. body=null 이면 변경 없음.
     */
    @PostMapping("/poll")
    public ApiResponse<Map<String, Object>> poll(@RequestBody Map<String, Object> req) {
        Object codeVal = req.get("code");
        if (codeVal == null) codeVal = req.get("storeCode");
        String storeCode = codeVal == null ? "" : String.valueOf(codeVal);
        String token = "";
        Object h = req.get("header");
        if (h instanceof Map) {
            Object t = ((Map<?, ?>) h).get("token");
            if (t != null) token = String.valueOf(t);
        }
        return ApiResponse.ok(service.poll(storeCode, token));
    }

    /** 단말의 수신·적용 완료 통지. */
    @PostMapping("/{id}/confirm")
    public ApiResponse<Void> confirm(@PathVariable Long id) {
        service.confirm(id);
        return ApiResponse.ok("배포 적용 확인 완료", null);
    }

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

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

    @PostMapping
    public ApiResponse<SignDeployVo> create(@RequestBody SignDeployVo v) {
        return ApiResponse.ok("간판정보 배포 생성 완료", service.create(v));
    }

    @PutMapping("/{id}")
    public ApiResponse<SignDeployVo> update(@PathVariable Long id, @RequestBody SignDeployVo v) {
        return ApiResponse.ok("간판정보 배포 수정 완료", service.update(id, v));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        service.delete(id);
        return ApiResponse.ok("간판정보 배포 삭제 완료", null);
    }
}
