package gateway

import (
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"strings"

	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/pkg/httpvalidation"
)

var (
	ErrInvalidRefreshRequest = errors.New("invalid refresh token request")
	ErrMissingRefreshToken   = errors.New("refresh token is required")
)

// RefreshTokenRequestDTO represents the refresh token request payload
type RefreshTokenRequestDTO struct {
	RefreshToken string `json:"refresh_token"`
}

// Validate validates the refresh token request
// CWE-20: Improper Input Validation - Validates refresh token presence
func (dto *RefreshTokenRequestDTO) Validate() error {
	// Validate refresh token (non-empty)
	if strings.TrimSpace(dto.RefreshToken) == "" {
		return ErrMissingRefreshToken
	}

	// Normalize token (trim whitespace)
	dto.RefreshToken = strings.TrimSpace(dto.RefreshToken)

	return nil
}

// ParseRefreshTokenRequest parses and validates a refresh token request from HTTP request body
func ParseRefreshTokenRequest(r *http.Request) (*RefreshTokenRequestDTO, error) {
	// CWE-436: Validate Content-Type before parsing
	if err := httpvalidation.RequireJSONContentType(r); err != nil {
		return nil, err
	}

	// Read body
	body, err := io.ReadAll(r.Body)
	if err != nil {
		return nil, ErrInvalidRefreshRequest
	}
	defer r.Body.Close()

	// Parse JSON
	var dto RefreshTokenRequestDTO
	if err := json.Unmarshal(body, &dto); err != nil {
		return nil, ErrInvalidRefreshRequest
	}

	// Validate
	if err := dto.Validate(); err != nil {
		return nil, err
	}

	return &dto, nil
}
