// 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 testing provides utilities for command-line-based testing.
package testing

import (
	"fmt"
	"slices"
	"strings"

	"github.com/release-argus/Argus/config"
	"github.com/release-argus/Argus/internal/logx"
)

// ServiceTest queries the service and returns the found version.
func ServiceTest(flag *string, cfg *config.Config) bool {
	// Only if flag provided.
	if *flag == "" {
		return true
	}

	// Log the test details.
	logFrom := logx.LogFrom{Primary: "Testing", Secondary: *flag}
	logx.Info(
		"",
		logFrom,
		true,
	)

	// Check service exists.
	if !slices.Contains(cfg.Order, *flag) {
		logx.Fatal(
			fmt.Sprintf(
				"Service %q could not be found in config.service\nDid you mean one of these?\n  - %s",
				*flag, strings.Join(cfg.Order, "\n  - "),
			),
			logFrom,
		)
		return false
	}

	// Service to test.
	svc := cfg.Service[*flag]

	// LatestVersion.
	_, err := svc.LatestVersion.Query(false, logFrom)
	if err != nil {
		logx.Error(
			fmt.Sprintf(
				"No version matching the conditions specified could be found for %q at %q",
				*flag, svc.LatestVersion.ServiceURL(),
			),
			logFrom,
			true,
		)
	}

	// DeployedVersionLookup.
	if svc.DeployedVersionLookup != nil {
		if err := svc.DeployedVersionLookup.Query(false, logFrom); err == nil {
			logx.Info(
				fmt.Sprintf("Deployed version - %q", svc.Status.DeployedVersion()),
				logFrom,
				true,
			)
		}
	}

	return true
}
