package handler

import (
	stdjson "encoding/json"
	"net/http"

	"github.com/gofrs/uuid/v5"
)

// CheckCreditLine checks if a company has enough credit for an order
func (h *Handler) CheckCreditLine(w http.ResponseWriter, r *http.Request) {
	companyIDStr := r.PathValue("company_id")
	companyID, err := uuid.FromString(companyIDStr)
	if err != nil {
		http.Error(w, "invalid company id", http.StatusBadRequest)
		return
	}

	var req struct {
		AmountCents int64 `json:"amount_cents"`
	}
	if err := stdjson.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	ok, err := h.svc.CheckCreditLine(r.Context(), companyID, req.AmountCents)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	stdjson.NewEncoder(w).Encode(map[string]bool{"available": ok})
}

// SetCreditLimit sets a company's credit limit (admin only)
func (h *Handler) SetCreditLimit(w http.ResponseWriter, r *http.Request) {
	companyIDStr := r.PathValue("company_id")
	companyID, err := uuid.FromString(companyIDStr)
	if err != nil {
		http.Error(w, "invalid company id", http.StatusBadRequest)
		return
	}

	var req struct {
		LimitCents int64 `json:"limit_cents"`
	}
	if err := stdjson.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	if err := h.svc.SetCreditLimit(r.Context(), companyID, req.LimitCents); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
	stdjson.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}
