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

import cn.reghao.jutil.jdk.web.result.Result;
import cn.reghao.tnb.common.web.WebResult;
import cn.reghao.tnb.auth.app.model.dto.VerifyCodeDto;
import cn.reghao.tnb.auth.api.dto.RsaPubkey;
import cn.reghao.tnb.auth.app.service.CodeService;
import cn.reghao.tnb.auth.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")
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 = "/code/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 = "/code/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 = "/code/verify", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getVerifyCode(@RequestBody @Validated VerifyCodeDto verifyCodeDto) {
        Result result = codeService.sendVerifyCode(verifyCodeDto);
        return WebResult.result(result);
    }
}
