package main

import (
	"strings"
	"testing"
)

// TestReleaseAPIURL pins the contract that downstream code (the updater and
// /install.sh) relies on: only https://host/owner/repo produces an API URL,
// everything else errors. Plain HTTP must be rejected — M7 makes auto-update
// only trust TLS-protected release feeds, since the binary it downloads is
// exec'd as root.
func TestReleaseAPIURL(t *testing.T) {
	tests := []struct {
		name    string
		in      string
		want    string
		wantErr string // substring expected in the error message; "" means success
	}{
		{
			name: "valid https repo",
			in:   "https://tea.example.com/owner/repo",
			want: "https://tea.example.com/api/v1/repos/owner/repo/releases/latest",
		},
		{
			name:    "http rejected",
			in:      "http://tea.example.com/owner/repo",
			wantErr: "https",
		},
		{
			name:    "ssh scheme rejected",
			in:      "ssh://tea.example.com/owner/repo",
			wantErr: "https",
		},
		{
			name:    "missing repo segment",
			in:      "https://tea.example.com/owner",
			wantErr: "owner/repo",
		},
		{
			name:    "extra path segments",
			in:      "https://tea.example.com/owner/repo/extra",
			wantErr: "owner/repo",
		},
		{
			name:    "empty",
			in:      "",
			wantErr: "https",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := releaseAPIURL(tt.in)
			if tt.wantErr == "" {
				if err != nil {
					t.Fatalf("unexpected error: %v", err)
				}
				if got != tt.want {
					t.Errorf("got %q, want %q", got, tt.want)
				}
				return
			}
			if err == nil {
				t.Fatalf("expected error containing %q, got nil (result %q)", tt.wantErr, got)
			}
			if !strings.Contains(err.Error(), tt.wantErr) {
				t.Errorf("error %q does not contain %q", err.Error(), tt.wantErr)
			}
		})
	}
}
