package com.zioinfo.cms.channel;

import com.zioinfo.cms.channel.mapper.ChannelMapper;
import com.zioinfo.cms.common.ApiResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/** 다채널 배포 타겟 API. */
@RestController
@RequestMapping("/api/cms/channel")
@RequiredArgsConstructor
public class ChannelController {

    private final ChannelMapper mapper;

    @GetMapping
    public ApiResponse<List<CmsChannel>> list() {
        return ApiResponse.ok(mapper.findAll());
    }

    @GetMapping("/{id}")
    public ApiResponse<CmsChannel> get(@PathVariable Long id) {
        CmsChannel c = mapper.findById(id);
        if (c == null) throw new RuntimeException("ERR-CMS-CHANNEL-404: 채널 없음");
        return ApiResponse.ok(c);
    }

    @PostMapping
    public ApiResponse<CmsChannel> create(@RequestBody Map<String, Object> req) {
        CmsChannel c = bind(new CmsChannel(), req);
        mapper.insert(c);
        return ApiResponse.ok(mapper.findById(c.getId()));
    }

    @PutMapping("/{id}")
    public ApiResponse<CmsChannel> update(@PathVariable Long id, @RequestBody Map<String, Object> req) {
        CmsChannel c = mapper.findById(id);
        if (c == null) throw new RuntimeException("ERR-CMS-CHANNEL-404: 채널 없음");
        bind(c, req);
        mapper.update(c);
        return ApiResponse.ok(mapper.findById(id));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        mapper.delete(id);
        return ApiResponse.ok(null);
    }

    private CmsChannel bind(CmsChannel c, Map<String, Object> r) {
        if (r.containsKey("name")) c.setName(str(r.get("name")));
        if (r.containsKey("channelType")) c.setChannelType(str(r.get("channelType")));
        if (r.containsKey("endpoint")) c.setEndpoint(str(r.get("endpoint")));
        if (r.containsKey("active")) c.setActive(Boolean.parseBoolean(String.valueOf(r.get("active"))));
        if (c.getChannelType() == null) c.setChannelType("WEB");
        return c;
    }

    private String str(Object o) { return o == null ? null : String.valueOf(o); }
}
