package infra

import (
	"fmt"
	"time"
)

// JobComplete marks a job as completed and stores the optional result JSON string.
// result may be empty ("") to indicate no result payload.
func JobComplete(q *JobQueue, jobID string, result string) error {
	if q == nil {
		return fmt.Errorf("job_complete: queue must not be nil")
	}
	if jobID == "" {
		return fmt.Errorf("job_complete: jobID must not be empty")
	}

	now := time.Now().UTC().Format(time.RFC3339)
	var resultPtr *string
	if result != "" {
		resultPtr = &result
	}

	query := fmt.Sprintf(`
UPDATE %s
SET status = 'completed', completed_at = ?, result = ?
WHERE id = ?
`, q.TableName)

	res, err := q.DB.Exec(query, now, resultPtr, jobID)
	if err != nil {
		return fmt.Errorf("job_complete: update: %w", err)
	}
	n, _ := res.RowsAffected()
	if n == 0 {
		return fmt.Errorf("job_complete: job %q not found", jobID)
	}
	return nil
}
