package handlers

import (
	"encoding/json"
	"net/http"
)

type OtpRequest struct {
	OpenID string `json:"openid"`
	Num    int    `json:"num"`
	Token  *[]OTP `json:"token"`
}
type OTP struct {
	Issuer string `json:"issuer"`
	Remark string `json:"remark"`
	Secret string `json:"secret"`
}

func (h *Handler) UpdateOrCreateOtp(w http.ResponseWriter, r *http.Request) {
	var req OtpRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "Invalid request payload", http.StatusBadRequest)
		return
	}

	num := len(*req.Token)

	// 插入或更新 OTP 记录
	query := `
		INSERT INTO otp (openid, num, token)
		VALUES ($1, $2, $3)
	`

	_, err := h.DB.Exec(query, req.OpenID, req.Token, num)
	if err != nil {
		http.Error(w, "Failed to update or create OTP", http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
	w.Write([]byte("OTP updated or created successfully"))
}

func (h *Handler) GetOtp(w http.ResponseWriter, r *http.Request) {
	openid := r.URL.Query().Get("openid")
	if openid == "" {
		http.Error(w, "未登录", http.StatusBadRequest)
		return
	}

	var otp OtpRequest

	err := h.DB.Get(&otp, "SELECT token, num, openid FROM otp WHERE openid=$1", openid)
	if err != nil {
		http.Error(w, "OTP not found", http.StatusNotFound)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(otp)
}