// 图片生成中转站适配器测试，验证任务提交、状态轮询及成功结果解析契约。
package apimart

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
)

// TestSubmitImageUsesGenerationEndpoint 验证图片生成使用配置渠道下的标准提交接口。
func TestSubmitImageUsesGenerationEndpoint(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
		if request.Method != http.MethodPost || request.URL.Path != "/v1/images/generations" {
			t.Fatalf("unexpected request: %s %s", request.Method, request.URL.Path)
		}
		fmt.Fprint(response, `{"code":200,"data":[{"status":"submitted","task_id":"task-image-1"}]}`)
	}))
	defer server.Close()

	result, err := NewClient(server.Client()).SubmitImage(context.Background(), server.URL+"/v1", "test-key", "request-1", map[string]any{"model": "gpt-image-2"})
	if err != nil {
		t.Fatalf("SubmitImage returned error: %v", err)
	}
	if result.TaskID != "task-image-1" {
		t.Fatalf("unexpected task id: %s", result.TaskID)
	}
}

// TestPollImageUsesTaskEndpoint 验证图片任务使用 APIMart 统一任务接口查询并解析完成结果。
func TestPollImageUsesTaskEndpoint(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
		if request.Method != http.MethodGet || request.URL.Path != "/v1/tasks/task-image-1" {
			t.Fatalf("unexpected request: %s %s", request.Method, request.URL.Path)
		}
		fmt.Fprint(response, `{"code":200,"data":{"id":"task-image-1","status":"completed","result":{"images":[{"url":["https://example.com/result.png"]}]}}}`)
	}))
	defer server.Close()

	result, err := NewClient(server.Client()).PollImage(context.Background(), server.URL+"/v1", "test-key", "task-image-1")
	if err != nil {
		t.Fatalf("PollImage returned error: %v", err)
	}
	if result.Status != "completed" || result.URL != "https://example.com/result.png" {
		t.Fatalf("unexpected result: %#v", result)
	}
}
