package store

import (
	"context"
	"strings"
)

type CompatibilitySubmission struct {
	TargetProtocol string
	PublicID       string
	SourceProtocol string
	HTTPStatus     int
	Headers        map[string]any
	Body           map[string]any
}

func (s *Store) SetTaskCompatibilitySubmission(ctx context.Context, taskID string, submission CompatibilitySubmission) error {
	_, err := s.pool.Exec(ctx, `
UPDATE gateway_tasks
SET compatibility_protocol = COALESCE(NULLIF($2, ''), compatibility_protocol),
    compatibility_public_id = NULL,
    compatibility_source_protocol = COALESCE(NULLIF($3, ''), compatibility_source_protocol),
    compatibility_submit_http_status = NULL,
    compatibility_submit_headers = '{}'::jsonb,
    compatibility_submit_body = '{}'::jsonb,
    updated_at = now()
WHERE id = $1::uuid`,
		taskID,
		strings.TrimSpace(submission.TargetProtocol),
		strings.TrimSpace(submission.SourceProtocol),
	)
	return err
}

func (s *Store) GetCompatibilityTask(ctx context.Context, protocol string, publicID string) (GatewayTask, error) {
	task, err := scanGatewayTask(s.pool.QueryRow(ctx, `
SELECT `+gatewayTaskColumns+`
FROM gateway_tasks
WHERE compatibility_protocol = $1
  AND (
    id::text = $2
    OR remote_task_id = $2
    OR compatibility_public_id = $2
  )
LIMIT 1`, strings.TrimSpace(protocol), strings.TrimSpace(publicID)))
	if err != nil {
		return GatewayTask{}, err
	}
	attempts, err := s.ListTaskAttempts(ctx, task.ID)
	if err != nil {
		return GatewayTask{}, err
	}
	task.Attempts = attempts
	return task, nil
}
