package plugin

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net"

	"git.optclblast.xyz/draincloud/draincloud-core/internal/plugin/domain"
)

type Plugin struct {
	conn net.Conn
	md   domain.InitPluginRequest
}

func (p *Plugin) Init(initPayload any) error {
	r := &domain.Ping{
		Payload: initPayload,
	}

	pingData, err := json.Marshal(r)
	if err != nil {
		return err
	}

	if _, err = p.conn.Write(pingData); err != nil {
		return err
	}

	pongData := make([]byte, 0)
	if _, err := p.conn.Read(pongData); err != nil {
		return err
	}

	if !bytes.Equal(pongData, pingData) {
		return fmt.Errorf("ping-pong payload assertion error")
	}

	return nil
}

func (p *Plugin) Close() error {
	return p.conn.Close()
}
