package handlers

import (
	"net/http"
	"otaupdate/services"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/httphandlers"
	"github.com/fiskerinc/cloud-services/pkg/loggerdataresp"
)

// HandleCustomerOtaEmails godoc
// @Summary Sends customer emails by list of vins
// @Description Sends OTA notification emails to all emails associated with vins in request body
// @Accept  json
// @Produce  json
// @Param Authorization header string false "Bearer <ID token>"
// @Param Api-Key header string false "<API token>"
// @Param data body common.CustomerOtaEmailsRequest true "Customer OTA Emails Request"
// @Success 200 {object} map[string]bool "Customer Ota Emails"
// @Failure 400 {object} common.JSONError "Bad request"
// @Failure 401 {object} common.JSONError "Unauthorized"
// @Failure 503 {object} common.JSONError "Service unavailable"
// @Router /customer_ota_emails [put]
func HandleCustomerOtaEmails(w http.ResponseWriter, r *http.Request) {
	var request common.CustomerOtaEmailsRequest
	err := httphandlers.ParseRequest(r, &request)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusBadRequest) {
		return
	}

	var fromEmail = "fastservice@ovloop.com"
	var toEmails = []string{}
	var subject = request.EmailSubject
	var body = request.EmailBody

	driverEmails, err := services.GetDB().GetDriverEmails().SelectByVINs(request.VINs)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable, loggerdataresp.PostgresNoRowsErrorCheck) {
		return
	}

	for _, driverEmail := range driverEmails {
		toEmails = append(toEmails, driverEmail.Email)
	}

	err = services.GetSMTP().Send(fromEmail, toEmails, subject, body)
	if loggerdataresp.BadDataErrorResp(w, err, http.StatusServiceUnavailable) {
		return
	}
}
