// Copyright [2026] [Argus]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package v1 provides the API for the webserver.
package v1

import (
	"net/url"

	"github.com/release-argus/Argus/config/decode"
	"github.com/release-argus/Argus/internal/logx"
	apitype "github.com/release-argus/Argus/web/api/types"
)

// marshalAnnouncePayload serialises WebSocket announce payloads (overridable for tests).
var marshalAnnouncePayload = func(v any) ([]byte, error) {
	return decode.Marshal("json", v)
}

// sendAnnouncePayload marshals a WebSocket message to JSON and publishes it on the announce channel.
// Marshal failures are logged and the message is dropped.
func (api *API) sendAnnouncePayload(msg apitype.WebSocketMessage) {
	payloadData, err := marshalAnnouncePayload(msg)
	if err != nil {
		logx.Error(err, logx.LogFrom{Primary: "API sendAnnouncePayload"}, true)
		return
	}
	api.Config.HardDefaults.Service.Status.AnnounceChannel <- payloadData
}

// getParam returns a query parameter value pointer if present, otherwise nil.
func getParam(queryParams url.Values, key string) *string {
	if !queryParams.Has(key) {
		return nil
	}

	val := queryParams.Get(key)
	return &val
}

// announceEdit broadcasts an EDIT message to all WebSocket clients.
//
// Only the fields the edit changed are sent; SubType carries the ID the service
// had before the edit (empty when it was created). An edit that changes nothing
// the dashboard displays still announces, with no ServiceData, so that clients
// invalidate their cached config for the service.
func (api *API) announceEdit(oldData *apitype.ServiceSummary, newData *apitype.ServiceSummary) {
	serviceChanged := ""
	if oldData != nil {
		serviceChanged = oldData.ID
		newData.RemoveUnchanged(oldData)
	}

	api.sendAnnouncePayload(
		apitype.WebSocketMessage{
			Page:        "APPROVALS",
			Type:        "EDIT",
			SubType:     serviceChanged,
			ServiceData: newData,
		},
	)
}

// announceDelete broadcasts a DELETE message to all WebSocket clients.
func (api *API) announceDelete(serviceID string) {
	api.sendAnnouncePayload(
		apitype.WebSocketMessage{
			Page:    "APPROVALS",
			Type:    "DELETE",
			SubType: serviceID,
		},
	)
}

// announceOrder broadcasts an ORDER message to all WebSocket clients.
func (api *API) announceOrder() {
	api.sendAnnouncePayload(
		apitype.WebSocketMessage{
			Page:    "APPROVALS",
			Type:    "SERVICE",
			SubType: "ORDER",
			Order:   &api.Config.Order,
		},
	)
}

// ConstantTimeCompare reports whether the arrays x and y have equal contents.
// The time taken depends only on the length of the arrays, not their contents.
func ConstantTimeCompare(x, y [32]byte) bool {
	var result byte

	for i := range len(x) {
		result |= x[i] ^ y[i]
	}

	return result == 0
}
