// Package service add by blacknc <blacknc@163.com> at 2023/06/16 14:43:29
package service

import (
	"context"
	dto "dataservices/internal/dto/dataapi_gateway"
	"dataservices/internal/entity"
	"dataservices/internal/repository"
	"encoding/json"

	"github.com/tidbcloud/tiinf/errs"
)

func HandleEndpointExecRecord(ctx context.Context, request *dto.HistoryRecordReq) error {

	var endpointRecord entity.EndpointExecRecord
	if err := json.Unmarshal([]byte(request.RecordContent), &endpointRecord); err != nil {
		return errs.NewBadRequest("invalid endpoint execute record info", err)
	}

	if err := checkEndpointRecord(endpointRecord); err != nil {
		return err
	}

	return repository.CreateEndpointExecRecord(ctx, &endpointRecord)
}

func checkEndpointRecord(endpointRecord entity.EndpointExecRecord) error {
	if endpointRecord.DataAppID == 0 {
		return errs.NewBadRequest("invalid param:dataapp_id", nil)
	}
	if endpointRecord.EndpointID == 0 {
		return errs.NewBadRequest("invalid param:endpoint_id", nil)
	}
	if endpointRecord.Type == "" {
		return errs.NewBadRequest("invalid param:type", nil)
	}
	if endpointRecord.Region == "" {
		return errs.NewBadRequest("invalid param:region", nil)
	}
	if endpointRecord.Caller == "" {
		return errs.NewBadRequest("invalid param:caller", nil)
	}
	if endpointRecord.Code == 0 {
		return errs.NewBadRequest("invalid param:code", nil)
	}
	return nil
}
