package httpapi

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/store"
)

func TestVolcesCompatibleTaskBuildsProtocolResponseFromCanonicalResult(t *testing.T) {
	now := time.Date(2026, 7, 18, 8, 0, 0, 0, time.UTC)
	task := store.GatewayTask{
		ID: "gateway-task-1", Kind: "videos.generations", Status: "succeeded", Model: "doubao-seedance-2-0-mini-260615",
		RemoteTaskID: "cgt-upstream-1", CreatedAt: now, UpdatedAt: now.Add(time.Second),
		Result: map[string]any{
			"id": "cgt-upstream-1", "model": "doubao-seedance-2-0-mini-260615", "status": "succeeded",
			"data":                  []any{map[string]any{"url": "https://example.com/out.mp4", "type": "video"}},
			"future_official_field": "not-whitelisted",
		},
		Usage:    map[string]any{"totalTokens": 9},
		Billings: []any{map[string]any{"amount": 3}}, BillingSummary: map[string]any{"currency": "resource"}, FinalChargeAmount: 3,
		Attempts: []store.TaskAttempt{{Provider: "volces"}},
	}
	got := volcesCompatibleTask(task)
	if got["id"] != task.RemoteTaskID || got["status"] != "succeeded" || got["future_official_field"] != nil {
		t.Fatalf("unexpected compatibility identity/status: %+v", got)
	}
	content, _ := got["content"].(map[string]any)
	if content["video_url"] != "https://example.com/out.mp4" || got["usage"] == nil {
		t.Fatalf("official fields were lost: %+v", got)
	}
	for _, forbidden := range []string{"gateway_task_id", "gateway_status", "billings", "billing_summary", "final_charge_amount", "upstream_task_id"} {
		if _, ok := got[forbidden]; ok {
			t.Fatalf("compatibility response contains gateway extension %q: %+v", forbidden, got)
		}
	}
}

func TestVolcesCompatibilityPreservesValidationGateStatus(t *testing.T) {
	recorder := httptest.NewRecorder()
	writeVolcesCompatibleTaskError(recorder, &gatewayTaskCreationError{
		Stage: gatewayTaskCreationPrepare,
		Err: &taskTrafficError{
			Status:  http.StatusServiceUnavailable,
			Code:    "validation_in_progress",
			Message: "new production tasks are paused while validation is running",
		},
	})
	if recorder.Code != http.StatusServiceUnavailable {
		t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
	}
	var payload VolcesErrorEnvelope
	if err := json.NewDecoder(recorder.Body).Decode(&payload); err != nil {
		t.Fatalf("decode error: %v", err)
	}
	if payload.Error.Code != "validation_in_progress" {
		t.Fatalf("error=%+v", payload.Error)
	}
}
