package text

import (
	"context"
	"fmt"
	"net/http"
	"time"

	"github.com/rs/zerolog/log"
	"github.com/twilio/twilio-go"
	twilioClient "github.com/twilio/twilio-go/client"
	twilioApi "github.com/twilio/twilio-go/rest/api/v2010"
	"source.gleipnir.technology/Gleipnir/nidus-sync/config"
)

// forceContextRoundTripper sets the given context on every request and passes it to the wrapped RoundTripper
type forceContextRoundTripper struct {
	roundTripper http.RoundTripper
	ctx          context.Context
}

func (f *forceContextRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	req = req.Clone(f.ctx)
	return f.roundTripper.RoundTrip(req)
}

func sendTextTwilio(ctx context.Context, source string, destination string, message string) (string, error) {
	ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
	defer cancel()

	client := twilio.NewRestClient()

	http_client := &http.Client{
		Timeout: 30 * time.Second,
	}
	http_client.Transport = &forceContextRoundTripper{
		ctx:          ctx,
		roundTripper: http_client.Transport,
	}
	client.RequestHandler.Client.(*twilioClient.Client).HTTPClient = http_client
	params := &twilioApi.CreateMessageParams{}
	params.SetMessagingServiceSid(config.TwilioMessagingServiceSID)

	params.SetBody(message)
	params.SetTo(destination)
	resp, err := client.Api.CreateMessage(params)

	if err != nil {
		return "", fmt.Errorf("Failed to create message to %s: %w", destination, err)
	}
	if resp.Sid == nil {
		log.Warn().Str("src", source).Str("dst", destination).Msg("Text message sid is nil")
		return "", nil
	}
	log.Info().Str("src", source).Str("dst", destination).Str("message", message).Str("sid", *resp.Sid).Msg("Created text message")
	return *resp.Sid, nil
}
