package store

import (
	"context"
	"strings"
)

// GetRuntimeModelCandidateForRemoteTask restores the exact platform model used
// to submit an asynchronous provider task. It deliberately ignores enabled
// state so a task can still be cancelled after its platform is disabled.
func (s *Store) GetRuntimeModelCandidateForRemoteTask(ctx context.Context, platformModelID string, platformID string) (RuntimeModelCandidate, bool, error) {
	platformModelID = strings.TrimSpace(platformModelID)
	platformID = strings.TrimSpace(platformID)
	if platformModelID == "" || platformID == "" {
		return RuntimeModelCandidate{}, false, nil
	}
	var candidate RuntimeModelCandidate
	var credentials, config []byte
	err := s.pool.QueryRow(ctx, `
SELECT p.id::text, p.platform_key, p.name, p.provider,
       COALESCE(NULLIF(p.config->>'specType', ''), p.provider), COALESCE(p.base_url, ''), p.auth_type,
       p.credentials, p.config, m.id::text, COALESCE(NULLIF(m.provider_model_name, ''), m.model_name),
       m.model_name, COALESCE(m.model_alias, ''),
       COALESCE((m.model_type->>0), 'video_generate')
FROM platform_models m
JOIN integration_platforms p ON p.id = m.platform_id
WHERE m.id = $1::uuid AND p.id = $2::uuid AND p.deleted_at IS NULL`, platformModelID, platformID).Scan(
		&candidate.PlatformID, &candidate.PlatformKey, &candidate.PlatformName, &candidate.Provider,
		&candidate.SpecType, &candidate.BaseURL, &candidate.AuthType, &credentials, &config,
		&candidate.PlatformModelID, &candidate.ProviderModelName, &candidate.ModelName, &candidate.ModelAlias, &candidate.ModelType,
	)
	if IsNotFound(err) {
		return RuntimeModelCandidate{}, false, nil
	}
	if err != nil {
		return RuntimeModelCandidate{}, false, err
	}
	candidate.Credentials = decodeObject(credentials)
	candidate.PlatformConfig = decodeObject(config)
	candidate.ClientID = candidate.PlatformKey + ":" + candidate.ModelType + ":" + firstNonEmpty(candidate.ProviderModelName, candidate.ModelName)
	candidate.QueueKey = candidate.ClientID
	return candidate, true, nil
}
