package exporter

import (
	"github.com/bytedance/sonic"

	"github.com/break/junhong_cmp_fiber/internal/model"
)

// ParseExportParams 从导出任务快照解析数据源执行参数。
func ParseExportParams(task *model.ExportTask) ExportParams {
	params := ExportParams{Filters: make(map[string]any)}
	if task == nil {
		return params
	}

	params.ScopeShopIDs = append(params.ScopeShopIDs, task.ScopeShopIDs...)
	params.UserType = task.CreatorUserType
	params.CreatorShopID = task.CreatorShopID

	var raw map[string]any
	if len(task.QueryJSON) == 0 {
		return params
	}
	if err := sonic.Unmarshal(task.QueryJSON, &raw); err != nil {
		return params
	}

	if filters, ok := raw["filters"].(map[string]any); ok {
		params.Filters = filters
	}
	params.ResolvedHeaders = headersFromRawQuery(raw)
	return params
}

// ResolvedHeadersFromTask 从任务 query_json 读取 dispatch 阶段固定的表头。
func ResolvedHeadersFromTask(task *model.ExportTask) []string {
	if task == nil || len(task.QueryJSON) == 0 {
		return nil
	}

	var raw map[string]any
	if err := sonic.Unmarshal(task.QueryJSON, &raw); err != nil {
		return nil
	}

	return headersFromRawQuery(raw)
}

func headersFromRawQuery(raw map[string]any) []string {
	values, ok := raw["resolved_headers"].([]any)
	if !ok {
		return nil
	}

	headers := make([]string, 0, len(values))
	for _, value := range values {
		if text, ok := value.(string); ok {
			headers = append(headers, text)
		}
	}
	return headers
}
