package logic

import (
	"context"
	"crypto/sha256"
	"encoding/json"
	"io"
	"net/http"

	"fusenapi/server/feishu-sync/internal/svc"
	"github.com/zeromicro/go-zero/core/logx"
)

type WebhookLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewWebhookLogic(ctx context.Context, svcCtx *svc.ServiceContext) *WebhookLogic {
	return &WebhookLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

type EncryptWebhookMsg struct {
	Encrypt string `json:"encrypt"` //加密的消息
}
type WebhookMsg struct {
	Type      string                 `json:"type"`
	Challenge string                 `json:"challenge"`
	Header    map[string]interface{} `json:"header"`
	Event     map[string]interface{} `json:"event"`
}

// webhook消息事件header(body参数)基础信息
type BaseWebhookMsgHeaderType struct {
	EventId    string `json:"event_id"`    //事件id(可作为消息唯一性确认)
	EventType  string `json:"event_type"`  //事件类型
	CreateTime string `json:"create_time"` //创建时间
	Token      string `json:"token"`       //事件token
	AppId      string `json:"app_id"`      //app id
	TenantKey  string `json:"tenant_key"`  //租户key
}

func (l *WebhookLogic) Webhook(w http.ResponseWriter, r *http.Request) {
	bodyBytes, err := io.ReadAll(r.Body)
	if err != nil {
		logx.Error("读取请求body失败", err)
		return
	}
	logx.Info("收到头消息:", r.Header)
	logx.Info("收到body消息:", string(bodyBytes))
	//验证消息合法性
	if !l.VerifyWebhook(r.Header, bodyBytes, "DmiHQ2bHhKiR3KK4tIjLShbs13eErxKA") {
		return
	}
	defer r.Body.Close()
	//如果只是验证http连接的消息
	var webhookMsg WebhookMsg
	if err = json.Unmarshal(bodyBytes, &webhookMsg); err != nil {
		logx.Error("反序列化请求body失败", err)
		return
	}
	//验证连接(直接返回)
	if webhookMsg.Type == "url_verification" {
		challengeRsp := map[string]string{
			"challenge": webhookMsg.Challenge,
		}
		b, _ := json.Marshal(challengeRsp)
		w.Write(b)
		return
	}

	headerByte, err := json.Marshal(webhookMsg.Header)
	if err != nil {
		logx.Error("序列化请求体header失败:", err)
		return
	}
	var msgHeader BaseWebhookMsgHeaderType
	if err = json.Unmarshal(headerByte, &msgHeader); err != nil {
		logx.Error("反序列化请求体中的header失败", err)
		return
	}
	switch msgHeader.EventType {
	case "contact.custom_attr_event.updated_v3": //成员字段管理属性变更事件
	case "contact.department.created_v3": //部门新建
	case "contact.department.deleted_v3": //部门删除
	case "contact.department.updated_v3": //部门信息变化
	case "contact.employee_type_enum.actived_v3": //启动人员类型事件
	case "contact.employee_type_enum.created_v3": //新建人员类型事件
	case "contact.employee_type_enum.deactivated_v3": //停用人员类型事件
	case "contact.employee_type_enum.deleted_v3": //删除人员类型事件
	case "contact.employee_type_enum.updated_v3": //修改人员类型名称事件
	case "contact.scope.updated_v3": //通讯录范围权限被更新
	case "contact.user.created_v3": //员工入职
	case "contact.user.deleted_v3": //员工离职
	case "contact.user.updated_v3": //员工信息变化

	}
	return
}

// 处理逻辑后 w,r 如:重定向, resp 必须重新处理
// func (l *WebhookLogic) AfterLogic(w http.ResponseWriter, r *http.Request, resp *basic.Response) {
// // httpx.OkJsonCtx(r.Context(), w, resp)
// }
func (l *WebhookLogic) VerifyWebhook(header http.Header, bodyBytes []byte, encryptKey string) bool {
	b := []byte(header.Get("X-Lark-Request-Timestamp") + header.Get("X-Lark-Request-Nonce") + encryptKey)
	b = append(b, bodyBytes...)
	h := sha256.New()
	_, err := h.Write(b)
	if err != nil {
		logx.Error(err)
		return false
	}
	hashKey := h.Sum(nil)
	if string(hashKey) != header.Get("X-Lark-Signature") {
		logx.Error("无效的消息", string(hashKey), ":-----:", header.Get("X-Lark-Signature"))
		return false
	}
	return true
}