package cn.reghao.devops.web.admin.sys.controller;

import cn.reghao.devops.web.admin.sys.db.repository.EmailAccountRepository;
import cn.reghao.devops.web.admin.sys.db.repository.NotifyReceiverRepository;
import cn.reghao.devops.web.admin.sys.model.vo.NotifyType;
import cn.reghao.devops.web.admin.sys.model.po.EmailAccount;
import cn.reghao.devops.web.admin.sys.model.po.NotifyReceiver;
import cn.reghao.jutil.jdk.result.WebResult;
import cn.reghao.jutil.jdk.string.StringRegexp;
import io.swagger.annotations.Api;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author reghao
 * @date 2024-01-26 20:52:54
 */
@Api(tags = "邮件帐号管理接口")
@RestController
@RequestMapping("/api/sys/notify/email")
public class EmailController {
    private final NotifyReceiverRepository notifyReceiverRepository;
    private final EmailAccountRepository emailAccountRepository;

    public EmailController(NotifyReceiverRepository notifyReceiverRepository,
                           EmailAccountRepository emailAccountRepository) {
        this.notifyReceiverRepository = notifyReceiverRepository;
        this.emailAccountRepository = emailAccountRepository;
    }

    @PostMapping(value = "/save", produces = MediaType.APPLICATION_JSON_VALUE)
    public String saveReceiver(@Validated EmailAccount emailAccount) {
        String email = emailAccount.getUsername();
        boolean matched = StringRegexp.matchEmail(email);
        if (!matched) {
            return WebResult.failWithMsg("邮箱地址格式不正确, 请检查");
        }

        List<EmailAccount> list = emailAccountRepository.findAll();
        if (!list.isEmpty()) {
            EmailAccount emailAccount1 = list.get(0);
            emailAccount1.setSmtp(emailAccount.getSmtp());
            emailAccount1.setUsername(emailAccount.getUsername());
            emailAccount1.setPassword(emailAccount.getPassword());
            emailAccount1.setPersonal(emailAccount.getPersonal());
            emailAccountRepository.save(emailAccount1);
        } else {
            emailAccountRepository.save(emailAccount);
        }

        return WebResult.success();
    }

    @DeleteMapping(value = "/delete/{username}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String deleteEmail(@PathVariable("username") String username) {
        NotifyReceiver notifyReceiver = notifyReceiverRepository.findByType(NotifyType.email.name());
        if (notifyReceiver != null) {
            return WebResult.failWithMsg("系统中存在接收通知的邮箱地址, 不能删除发送通知的邮箱");
        }

        List<EmailAccount> list = emailAccountRepository.findAll();
        emailAccountRepository.delete(list.get(0));
        return WebResult.success();
    }
}
