package server

import (
	"context"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"time"

	"github.com/rjNemo/rentease/internal/service/booking"
)

type stripeSyncRequest struct {
	From string `json:"from"`
	To   string `json:"to"`
}

type stripeSyncer interface {
	SyncStripePayments(ctx context.Context, from, to time.Time) error
}

func handleStripeSync(bs stripeSyncer) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		req := new(stripeSyncRequest)
		if err := json.NewDecoder(r.Body).Decode(req); err != nil {
			if !errors.Is(err, io.EOF) {
				http.Error(w, "invalid request payload", http.StatusBadRequest)
				return
			}
		}

		now := time.Now().UTC()
		from := now.Add(-24 * time.Hour)
		to := now

		if req.From != "" {
			parsed, err := time.Parse(time.RFC3339, req.From)
			if err != nil {
				http.Error(w, "invalid 'from' timestamp, expected RFC3339", http.StatusBadRequest)
				return
			}
			from = parsed
		}

		if req.To != "" {
			parsed, err := time.Parse(time.RFC3339, req.To)
			if err != nil {
				http.Error(w, "invalid 'to' timestamp, expected RFC3339", http.StatusBadRequest)
				return
			}
			to = parsed
		}

		if err := bs.SyncStripePayments(r.Context(), from, to); err != nil {
			if errors.Is(err, booking.ErrStripeClientNotConfigured) {
				http.Error(w, "stripe client not configured", http.StatusServiceUnavailable)
				return
			}
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		if err := json.NewEncoder(w).Encode(map[string]string{"status": "ok"}); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	}
}
