package com.njcn.msgpush.module.push.controller.admin.message;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njcn.msgpush.framework.common.exception.enums.GlobalErrorCodeConstants;
import com.njcn.msgpush.framework.common.pojo.CommonResult;
import com.njcn.msgpush.framework.idempotent.core.annotation.Idempotent;
import com.njcn.msgpush.module.push.controller.admin.message.vo.MessageRecordReqVO;
import com.njcn.msgpush.module.push.controller.admin.message.vo.MessageSendResultVO;
import com.njcn.msgpush.module.push.dal.dataobject.message.MessageRecordDO;
import com.njcn.msgpush.module.push.enums.ChannelTypeEnum;
import com.njcn.msgpush.module.push.service.credential.CredentialServiceImpl;
import com.njcn.msgpush.module.push.service.credential.ICredentialService;
import com.njcn.msgpush.module.push.service.message.MessageRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static com.njcn.msgpush.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 消息")
@Validated
@RestController
@RequestMapping("/push/message")
public class MessageRecordController {

    @Autowired
    private MessageRecordService messageRecordService;
    @Autowired
    private ICredentialService credentialService;

    @PermitAll
    @PostMapping("/send/sms")
    @Operation(summary = "短信推送")
    @Idempotent(timeout = 2)
    public CommonResult<List<MessageSendResultVO>> sendSms(@Valid @RequestBody List<MessageRecordReqVO> reqVOList,
                                                           @RequestHeader(value = "X-Credential-Token", required = true) String credentialToken) {
        return doSend(reqVOList, credentialToken, ChannelTypeEnum.SMS);
    }

    @PermitAll
    @PostMapping("/send/email")
    @Operation(summary = "邮件推送")
    @Idempotent(timeout = 2)
    public CommonResult<List<MessageSendResultVO>> sendEmail(@Valid @RequestBody List<MessageRecordReqVO> reqVOList,
                                                             @RequestHeader(value = "X-Credential-Token", required = true) String credentialToken) {
        return doSend(reqVOList, credentialToken, ChannelTypeEnum.EMAIL);
    }

    @PermitAll
    @PostMapping("/send/app")
    @Operation(summary = "APP 推送")
    @Idempotent(timeout = 2)
    public CommonResult<List<MessageSendResultVO>> sendApp(@Valid @RequestBody List<MessageRecordReqVO> reqVOList,
                                                           @RequestHeader(value = "X-Credential-Token", required = true) String credentialToken) {
        return doSend(reqVOList, credentialToken, ChannelTypeEnum.APP);
    }

    private CommonResult<List<MessageSendResultVO>> doSend(List<MessageRecordReqVO> reqVOList,
                                                           String credentialToken,
                                                           ChannelTypeEnum channelTypeEnum) {
        CredentialServiceImpl.CredentialInfo credentialInfo = credentialService.verifyCredential(credentialToken);
        if (credentialInfo == null) {
            return CommonResult.error(GlobalErrorCodeConstants.UNAUTHORIZED.getCode(), "凭证无效或已过期");
        }
        return success(messageRecordService.send(reqVOList, channelTypeEnum, credentialInfo.getSystemName()));
    }

    @PostMapping("/page")
    @Operation(summary = "分页查询消息记录")
    @PreAuthorize("@ss.hasPermission('push:message:page')")
    public CommonResult<Page<MessageRecordDO>> pageChannelProviderConfig(@Validated @RequestBody MessageRecordReqVO reqVO) {
        return success(messageRecordService.getPage(reqVO));
    }

    @PostMapping("/add")
    @Operation(summary = "新增消息记录")
    @PreAuthorize("@ss.hasPermission('push:message:add')")
    public CommonResult<Boolean> add(@Validated @RequestBody MessageRecordReqVO reqVO) {
        return success(messageRecordService.add(reqVO));
    }

    @PostMapping("/update")
    @Operation(summary = "更新消息记录")
    @PreAuthorize("@ss.hasPermission('push:message:update')")
    public CommonResult<Boolean> update(@Validated @RequestBody MessageRecordReqVO reqVO) {
        MessageRecordDO messageRecordDO = BeanUtil.copyProperties(reqVO, MessageRecordDO.class);
        return success(messageRecordService.updateById(messageRecordDO));
    }

    @PostMapping("/delete")
    @Operation(summary = "删除消息记录")
    @PreAuthorize("@ss.hasPermission('push:message:delete')")
    @Parameter(name = "ids", description = "编号", required = true)
    public CommonResult<Boolean> delete(@RequestParam("ids") List<Long> ids) {
        return success(messageRecordService.removeByIds(ids));
    }
}
