package plugin

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

func convertFields(in []byte) ([]byte, error) {
	var msg MessageKong
	if err := json.Unmarshal(in, &msg); err != nil {
		return nil, err
	}

	// skip auditing for `GET` requests
	if msg.Request.Method == http.MethodGet {
		return nil, nil
	}

	out := Message{
		Timestamp:      msg.StartedAt,
		ClientIP:       msg.ClientIP,
		RequestURI:     msg.Request.URI,
		RequestMethod:  msg.Request.Method,
		RequestParams:  msg.Request.QueryString,
		RequestBody:    "", // this field is empty now
		RequestSize:    msg.Request.Size,
		ResponseStatus: msg.Response.Status,
		ResponseSize:   msg.Response.Size,
		Service:        msg.Service.Host,
		Latencies:      msg.Latencies,
	}

	res, err := json.Marshal(out)
	if err != nil {
		return nil, err
	}
	return res, nil
}

// MessageKong represents a log message of Kong.
// NOTE: only part of the log fields are included.
type MessageKong struct {
	StartedAt uint64    `json:"started_at"`
	ClientIP  string    `json:"client_ip"`
	Request   Request   `json:"request"`
	Response  Response  `json:"response"`
	Service   Service   `json:"service"`
	Latencies Latencies `json:"latencies"`
}

type Request struct {
	URI         string            `json:"uri"`
	Method      string            `json:"method"`
	QueryString map[string]string `json:"querystring"`
	Size        uint64            `json:"size"`
}

type Response struct {
	Status int    `json:"status"`
	Size   uint64 `json:"size"`
}

type Service struct {
	Host string `json:"host"`
}

type Latencies struct {
	Request int `json:"request"`
	Kong    int `json:"kong"`
	Proxy   int `json:"proxy"`
}

// Message represents a log message with our converted fields.
type Message struct {
	Timestamp      uint64            `json:"timestamp"`
	ClientIP       string            `json:"client_ip"`
	RequestURI     string            `json:"request_uri"`
	RequestMethod  string            `json:"request_method"`
	RequestParams  map[string]string `json:"request_params"`
	RequestBody    string            `json:"request_body"` // this field is empty now
	RequestSize    uint64            `json:"request_size"`
	ResponseStatus int               `json:"response_status"`
	ResponseSize   uint64            `json:"response_size"`
	Service        string            `json:"service"`
	Latencies      Latencies         `json:"latencies"`
}
