package cn.reghao.bnt.web.admin.controller;

import cn.reghao.bnt.web.admin.db.repository.WebhookRepository;
import cn.reghao.bnt.web.admin.model.po.Webhook;
import cn.reghao.bnt.web.admin.service.NotifyService;
import cn.reghao.bnt.web.admin.service.notifier.ding.DingMsg;
import cn.reghao.bnt.web.devops.app.model.vo.msg.DingTestMsg;
import cn.reghao.jutil.web.WebResult;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author reghao
 * @date 2021-04-04 21:24:18
 */
@Tag(name = "系统通知配置页面和接口")
@RestController
@RequestMapping("/api/devops/sys/notify/webhook")
@Slf4j
public class SysNotifyController {
    private final WebhookRepository webhookRepository;
    private final NotifyService notifyService;

    public SysNotifyController(WebhookRepository webhookRepository, NotifyService notifyService) {
        this.webhookRepository = webhookRepository;
        this.notifyService = notifyService;
    }

    @Operation(summary = "webhook 通知列表页面", description = "N")
    @GetMapping("")
    public String receiverIndex() {
        int pageNumber = 1;
        int pageSize = 10;
        PageRequest pageRequest = PageRequest.of(pageNumber-1, pageSize);
        Page<Webhook> page = webhookRepository.findAll(pageRequest);
        return WebResult.success(page.getContent());
    }

    @Operation(summary = "添加 webhook 通知接口", description = "N")
    @PostMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
    public String addWebhook(@Validated Webhook webhook) {
        String name = webhook.getName();
        Webhook webhookEntity = webhookRepository.findByName(name);
        if (webhookEntity != null) {
            return WebResult.failWithMsg(String.format("webhook 名字 %s 已存在", name));
        }

        webhookRepository.save(webhook);
        return WebResult.success();
    }

    @Operation(summary = "删除 webhook 通知接口", description = "N")
    @PostMapping(value = "/delete", produces = MediaType.APPLICATION_JSON_VALUE)
    public String deleteReceiver(Integer id) {
        Webhook webhook = webhookRepository.getById(id);
        webhookRepository.delete(webhook);
        return WebResult.success();
    }

    @Operation(summary = "测试 webhook 是否可用", description = "N")
    @PostMapping(value = "/test", produces = MediaType.APPLICATION_JSON_VALUE)
    public String testWebhook(Integer id) {
        Webhook webhook = webhookRepository.getById(id);
        DingMsg dingMsg = new DingTestMsg().dingMsg();
        notifyService.notify(webhook, dingMsg);
        return WebResult.successWithMsg("通知已发送");
    }
}
