package routes

import (
	"bssapp-backend/models"
	"bssapp-backend/queries"
	"database/sql"
	"encoding/json"
	"fmt"
	"net/http"
)

type validateOrderRequest struct {
	Header models.OrderHeader   `json:"header"`
	Lines  []models.OrderDetail `json:"lines"`
}

type validateOrderResponse struct {
	OK      bool                    `json:"ok"`
	Invalid []models.InvalidVariant `json:"invalid"`
}

func ValidateOrderHandler(mssql *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		var req validateOrderRequest
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			http.Error(w, fmt.Sprintf("JSON parse hatası: %v", err), http.StatusBadRequest)
			return
		}

		invalid, err := queries.ValidateOrderVariants(mssql, req.Lines)
		if err != nil {
			http.Error(w, fmt.Sprintf("Validate error: %v", err), http.StatusInternalServerError)
			return
		}

		resp := validateOrderResponse{
			OK:      len(invalid) == 0,
			Invalid: invalid,
		}

		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		_ = json.NewEncoder(w).Encode(resp)
	}
}
