package infra

import (
	"fmt"
	"time"

	"github.com/google/uuid"
)

// JobEnqueue inserts a new job into the queue and returns its UUID.
// jobType identifies the kind of work (e.g. "send_email", "resize_image").
// payload is a JSON string with the job data (defaults to "{}" if empty).
// Options: WithPriority, WithScheduledAt, WithMaxAttempts.
func JobEnqueue(q *JobQueue, jobType string, payload string, opts ...EnqueueOption) (string, error) {
	if q == nil {
		return "", fmt.Errorf("job_enqueue: queue must not be nil")
	}
	if jobType == "" {
		return "", fmt.Errorf("job_enqueue: jobType must not be empty")
	}
	if payload == "" {
		payload = "{}"
	}

	cfg := &enqueueConfig{
		priority:    0,
		scheduledAt: time.Now().UTC(),
		maxAttempts: 3,
	}
	for _, o := range opts {
		o(cfg)
	}

	id := uuid.New().String()
	scheduledAt := cfg.scheduledAt.Format(time.RFC3339)

	q2 := fmt.Sprintf(`
INSERT INTO %s (id, type, payload, status, priority, max_attempts, scheduled_at)
VALUES (?, ?, ?, 'pending', ?, ?, ?)
`, q.TableName)

	_, err := q.DB.Exec(q2, id, jobType, payload, cfg.priority, cfg.maxAttempts, scheduledAt)
	if err != nil {
		return "", fmt.Errorf("job_enqueue: insert: %w", err)
	}
	return id, nil
}
