package client

import (
	"fmt"
	"net/http"
	"net/url"
	"strconv"
)

func (c *Client) CreateQueryJob(req CreateQueryJobRequest) (*http.Response, error) {
	return c.DoJSON(http.MethodPost, "/jobs/query", req)
}

func (c *Client) GetQueryJob(jobID string) (*http.Response, error) {
	return c.DoJSON(http.MethodGet, "/jobs/query/"+url.PathEscape(jobID), nil)
}

func (c *Client) GetQueryResults(jobID string, params *GetQueryResultsParams) (*http.Response, error) {
	path := "/jobs/query/" + url.PathEscape(jobID) + "/results"
	if params != nil {
		values := url.Values{}
		if params.MaxRecords != nil {
			values.Set("maxRecords", strconv.Itoa(*params.MaxRecords))
		}
		if params.Locator != nil {
			values.Set("locator", *params.Locator)
		}
		if encoded := values.Encode(); encoded != "" {
			path += "?" + encoded
		}
	}
	return c.Do(http.MethodGet, path, "", nil)
}

func (c *Client) CreateIngestJob(req CreateIngestJobRequest) (*http.Response, error) {
	return c.DoJSON(http.MethodPost, "/jobs/ingest", req)
}

func (c *Client) GetIngestJob(jobID string) (*http.Response, error) {
	return c.DoJSON(http.MethodGet, "/jobs/ingest/"+url.PathEscape(jobID), nil)
}

func (c *Client) CloseIngestJob(jobID string, req UpdateJobStateRequest) (*http.Response, error) {
	return c.DoJSON(http.MethodPatch, "/jobs/ingest/"+url.PathEscape(jobID), req)
}

func (c *Client) UploadIngestJobData(jobID, csvBody string) (*http.Response, error) {
	return c.DoCSV(http.MethodPut, "/jobs/ingest/"+url.PathEscape(jobID)+"/batches", csvBody)
}

func QueryJobPath(jobID string) string {
	return fmt.Sprintf("/services/data/v63.0/jobs/query/%s", url.PathEscape(jobID))
}
