package apiv1

import (
	"log"
	"net/http"

	"code.secondbit.org/api.hg"
	"code.secondbit.org/ducky/devices.hg"

	"golang.org/x/net/context"
)

type createRequest struct {
	Devices []DeviceChange `json:"devices"`
}

func handleCreateDevices(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	var req createRequest
	var resp Response
	err := api.Decode(r, &req)
	if err != nil {
		api.Encode(w, r, http.StatusBadRequest, Response{Errors: api.InvalidFormatError})
		return
	}

	devicesToCreate := createDevicesFromChanges(req.Devices)
	for _, device := range devicesToCreate {
		err := validateDeviceCreation(device)
		if err != nil {
			// BUG(paddy): We still need to expose the validation error
			return
		}
	}
	createdDevices, err := devices.CreateMany(devicesToCreate, ctx)
	if err != nil {
		// BUG(paddy): we should filter out non-internal errors here and expose better error responses
		log.Printf("Error creating devices: %+v\n", err)
		api.Encode(w, r, http.StatusInternalServerError, Response{Errors: api.ActOfGodError})
		return
	}
	for _, device := range createdDevices {
		resp.Devices = append(resp.Devices, apiDeviceFromCore(device, api.CheckScopes(r, ScopeViewPushToken.ID)))
	}
	api.Encode(w, r, http.StatusCreated, resp)
}
