package cn.reghao.tnb.account.app.controller;

import cn.reghao.jutil.jdk.result.Result;
import cn.reghao.jutil.web.WebResult;
import cn.reghao.tnb.account.api.dto.VerifyCode;
import cn.reghao.tnb.account.api.dto.RsaPubkey;
import cn.reghao.tnb.account.app.service.CodeService;
import cn.reghao.tnb.account.app.service.PubkeyService;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @author reghao
 * @date 2022-02-18 16:05:30
 */
@Tag(name = "验证码接口")
@RestController
@RequestMapping("/api/auth/code")
public class AccountCodeController {
    private final CodeService codeService;
    private final PubkeyService pubkeyService;

    public AccountCodeController(CodeService codeService, PubkeyService pubkeyService) {
        this.codeService = codeService;
        this.pubkeyService = pubkeyService;
    }

    @Operation(summary = "获取加密需要的公钥", description = "N")
    @GetMapping(value = "/pubkey", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getPubkey(@RequestParam("channel") Integer channel) throws NoSuchAlgorithmException {
        RsaPubkey rsaPubkey = pubkeyService.getPubkey();
        return WebResult.success(rsaPubkey);
    }

    @Operation(summary = "获取图形验证码", description = "N")
    @GetMapping(value = "/captcha", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getCaptcha() throws IOException {
        InputStream in = codeService.generateCaptcha();
        byte[] base64Bytes = Base64.getEncoder().encode(in.readAllBytes());
        String base64Str = new String(base64Bytes, StandardCharsets.UTF_8);
        String imageStr = String.format("data:image/jpeg;base64,%s", base64Str);
        return WebResult.success(imageStr);
    }

    @Operation(summary = "获取短信/邮件验证码", description = "N")
    @PostMapping(value = "/verify", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getVerifyCode(@RequestBody @Validated VerifyCode verifyCode) {
        Result result = codeService.sendVerifyCode(verifyCode);
        return WebResult.result(result);
    }
}
