package service

import (
	"context"
	"net/url"
	"testing"
)

func TestBuildActionURLWithToken(t *testing.T) {
	t.Parallel()

	svc := NewWOPIService(WOPIConfig{
		PublicBaseURL: "https://api-wfm-dev.mybit.co.id",
		EditActionURL: "https://collabora.mybit.co.id/browser/abc/cool.html?",
	})

	// access_token_ttl is an absolute expiry time in epoch milliseconds.
	const accessTokenTTL = int64(1782971996000)
	got, err := svc.BuildActionURLWithToken(
		context.Background(),
		"019f1c17-b244-76c3-a1c0-6b3b382ad8b6",
		"jwt-token-value",
		accessTokenTTL,
	)
	if err != nil {
		t.Fatalf("BuildActionURLWithToken error = %v", err)
	}

	parsed, err := url.Parse(got)
	if err != nil {
		t.Fatalf("url.Parse error = %v", err)
	}

	// access_token and access_token_ttl must be SEPARATE top-level params so
	// Collabora echoes them back on every WOPI callback.
	if q := parsed.Query().Get("access_token"); q != "jwt-token-value" {
		t.Fatalf("unexpected access_token: %q", q)
	}
	if q := parsed.Query().Get("access_token_ttl"); q != "1782971996000" {
		t.Fatalf("unexpected access_token_ttl: %q", q)
	}

	// WOPISrc must be the BARE file URL — no token embedded inside it.
	wopiSrc := parsed.Query().Get("WOPISrc")
	if wopiSrc != "https://api-wfm-dev.mybit.co.id/wopi/files/019f1c17-b244-76c3-a1c0-6b3b382ad8b6" {
		t.Fatalf("WOPISrc must be the bare file url, got %q", wopiSrc)
	}
	if inner, err := url.Parse(wopiSrc); err == nil {
		if tok := inner.Query().Get("access_token"); tok != "" {
			t.Fatalf("WOPISrc must not embed access_token, got %q", tok)
		}
	}
}
