package com.backendsys.controller.KeyPair;

import com.backendsys.entity.KeyPair.DecryptedContentDTO;
import com.backendsys.entity.KeyPair.EncryptedContentDTO;
import com.backendsys.exception.CustException;
import com.backendsys.service.KeyPair.KeyPairService;
import com.backendsys.utils.response.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.util.Map;

@RestController
public class KeyPairController {

    @Autowired
    private KeyPairService keyPairService;

    /**
     * 获得密钥对（公钥、私钥）
     */
    @GetMapping("/api/public/generateKeyPair")
    public Result generateKeyPair() {
        return Result.success(keyPairService.generateKeyPair());
    }

    /**
     * 使用公钥来加密数据
     */
    @PostMapping("/api/public/encryptedContent")
    public Result encryptedContent(@RequestBody EncryptedContentDTO encryptedContentDTO) {
        String content = encryptedContentDTO.getContent();
        String public_key_str = encryptedContentDTO.getPublic_key();
        try {
            // (公钥) 将 Base64 转回 Byte
            PublicKey public_key = keyPairService.getPublicBase64ToByte(public_key_str);
            // 使用公钥来加密数据
            String content_encrypted = keyPairService.encryptedRSA(public_key, content);
            return Result.success(Map.of("content_encrypted", content_encrypted));
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new CustException(e.getMessage());
        }
    }

    /**
     * 使用私钥来解密数据
     */
    @PostMapping("/api/public/decryptedContent")
    public Result decryptedContent(@RequestBody DecryptedContentDTO decryptedContentDTO) {
        String content_encrypted = decryptedContentDTO.getContent_encrypted();
        String private_key_str = decryptedContentDTO.getPrivate_key();
        try {
            // (私钥) 将 Base64 转回 Byte
            PrivateKey private_key = keyPairService.getPrivateBase64ToByte(private_key_str);
            // 使用私钥来加密数据
            return Result.success(Map.of("content", keyPairService.decryptedRSA(private_key, content_encrypted)));
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            throw new CustException(e.getMessage());
        }
    }






}
