package events

import (
	"agent/commons/utils"
	"agent/defines/devent/daction"
	"agent/defines/devent/dcategory"
	"encoding/json"
)

func IsReloginEvent(event IEvent) bool {
	if utils.SliceEqual(event.Category(), []EventCategory{dcategory.Command}) {
		return event.Action() == daction.Relogin
	}
	// Такое возможно, если ивент пришёл в режиме DataOnly
	if event.Kind() == 0 {
		return isRelogin(event)
	}
	return false
}

type eventReloginResult struct {
	Type     string
	Category string
	Action   string
}

func (r eventReloginResult) MarshalJSON() ([]byte, error) {
	jsonData := map[string]any{
		"type":     r.Type,
		"category": r.Category,
		"action":   r.Action,
	}
	return json.Marshal(jsonData)
}

func (r *eventReloginResult) UnmarshalJSON(data []byte) error {
	jsonData := map[string]any{}
	if err := json.Unmarshal(data, &jsonData); err != nil {
		return err
	}
	if val, ok := jsonData["type"].(string); ok {
		r.Type = val
	}
	if val, ok := jsonData["category"].(string); ok {
		r.Category = val
	}
	if val, ok := jsonData["action"].(string); ok {
		r.Action = val
	}
	return nil
}

func isRelogin(event IEvent) (ok bool) {
	data, err := event.Data2()
	if err != nil {
		return false
	}
	var res eventReloginResult
	if err = json.Unmarshal(data, &res); err != nil {
		return false
	}
	if res.Type == "event" && res.Category == "command" && res.Action == "relogin" {
		return true
	}
	return false
}
