package routers

import (
	"encoding/json"
	"net/http"
	tasks "queues-go/app/storage/mongo/collections"
	"time"
)

type PutRequestBody struct {
	Payload          json.RawMessage `json:"payload"`
	SecondsToExecute int             `json:"seconds_to_execute"`
	Delay            *int            `json:"delay"`
}

func Put(w http.ResponseWriter, r *http.Request) {
	d := json.NewDecoder(r.Body)
	body := PutRequestBody{}
	err := d.Decode(&body)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	queue := r.Header.Get("queue")
	var availableFrom time.Time
	if body.Delay == nil {
		availableFrom = time.Now()
	} else {
		availableFrom = time.Now().Add(time.Second + time.Duration(*body.Delay))
	}
	task := tasks.InsertedTask{
		Queue:            queue,
		Payload:          body.Payload,
		PutAt:            time.Now(),
		AvailableFrom:    availableFrom,
		SecondsToExecute: body.SecondsToExecute,
		TakenAt:          nil,
		Attempts:         0,
	}
	err = tasks.Add(task)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusAccepted)
}
