package appsec

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

	"github.com/akamai/AkamaiOPEN-edgegrid-golang/v12/pkg/session"
	validation "github.com/go-ozzo/ozzo-validation/v4"
)

type (
	// The MalwareContentTypes interface supports retrieving the malware protection content types for a configuration and version.
	MalwareContentTypes interface {
		// GetMalwareContentTypes retrieves the available content types for malware protection.
		//
		// See: https://techdocs.akamai.com/application-security/reference/get-malware-policy-content-types
		GetMalwareContentTypes(ctx context.Context, params GetMalwareContentTypesRequest) (*GetMalwareContentTypesResponse, error)
	}

	// GetMalwareContentTypesRequest is used to retrieve the content types for a configuration version.
	GetMalwareContentTypesRequest struct {
		ConfigID int
		Version  int
	}

	// GetMalwareContentTypesResponse is returned from a call to GetMalwareContentTypes.
	GetMalwareContentTypesResponse struct {
		ContentTypes []string `json:"malwareContentTypes"`
	}
)

// Validate validates a GetMalwareContentTypesRequest.
func (v GetMalwareContentTypesRequest) Validate() error {
	return validation.Errors{
		"ConfigID": validation.Validate(v.ConfigID, validation.Required),
		"Version":  validation.Validate(v.Version, validation.Required),
	}.Filter()
}

func (p *appsec) GetMalwareContentTypes(ctx context.Context, params GetMalwareContentTypesRequest) (*GetMalwareContentTypesResponse, error) {
	logger := p.Log(ctx)
	logger.Debug("GetMalwareContentTypes")

	if err := params.Validate(); err != nil {
		return nil, fmt.Errorf("%w: %s", ErrStructValidation, err.Error())
	}

	uri := fmt.Sprintf(
		"/appsec/v1/configs/%d/versions/%d/malware-policies/content-types",
		params.ConfigID,
		params.Version,
	)

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
	if err != nil {
		return nil, fmt.Errorf("failed to create GetMalwareContentTypes request: %w", err)
	}

	var result GetMalwareContentTypesResponse
	resp, err := p.Exec(req, &result)
	if err != nil {
		return nil, fmt.Errorf("get malware content types request failed: %w", err)
	}
	defer session.CloseResponseBody(resp)

	if resp.StatusCode != http.StatusOK {
		return nil, p.Error(resp)
	}

	return &result, nil
}
