package store

import (
	"context"
	"encoding/json"
	"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 {
	headers, _ := json.Marshal(emptyObjectIfNil(submission.Headers))
	body, _ := json.Marshal(emptyObjectIfNil(submission.Body))
	_, err := s.pool.Exec(ctx, `
UPDATE gateway_tasks
SET compatibility_protocol = NULLIF($2, ''),
    compatibility_public_id = NULLIF($3, ''),
    compatibility_source_protocol = NULLIF($4, ''),
    compatibility_submit_http_status = NULLIF($5, 0),
    compatibility_submit_headers = $6::jsonb,
    compatibility_submit_body = $7::jsonb,
    updated_at = now()
WHERE id = $1::uuid`,
		taskID,
		strings.TrimSpace(submission.TargetProtocol),
		strings.TrimSpace(submission.PublicID),
		strings.TrimSpace(submission.SourceProtocol),
		submission.HTTPStatus,
		string(headers),
		string(body),
	)
	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 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
}
