package raft

import (
	"encoding/json"
)

// Codec defines the interface for encoding/decoding messages
type Codec interface {
	Marshal(v interface{}) ([]byte, error)
	Unmarshal(data []byte, v interface{}) error
	Name() string
}

// JSONCodec implements Codec using JSON encoding
type JSONCodec struct{}

func (c *JSONCodec) Marshal(v interface{}) ([]byte, error) {
	return json.Marshal(v)
}

func (c *JSONCodec) Unmarshal(data []byte, v interface{}) error {
	return json.Unmarshal(data, v)
}

func (c *JSONCodec) Name() string {
	return "json"
}

// DefaultCodec is the default codec used for serialization
// Change this to use a different codec (e.g., msgpack for better performance)
var DefaultCodec Codec = &JSONCodec{}

// SetCodec sets the default codec for serialization
// Note: This should be called before creating any Raft instances
func SetCodec(codec Codec) {
	DefaultCodec = codec
}

// MsgpackCodec implements Codec using msgpack encoding
// To use msgpack, import github.com/vmihailenco/msgpack/v5 and implement:
//
// import "github.com/vmihailenco/msgpack/v5"
//
// type MsgpackCodec struct{}
//
// func (c *MsgpackCodec) Marshal(v interface{}) ([]byte, error) {
//     return msgpack.Marshal(v)
// }
//
// func (c *MsgpackCodec) Unmarshal(data []byte, v interface{}) error {
//     return msgpack.Unmarshal(data, v)
// }
//
// func (c *MsgpackCodec) Name() string {
//     return "msgpack"
// }
//
// Then call: raft.SetCodec(&MsgpackCodec{})
