package binding

import "github.com/tidbcloud/AgentTeam/internal/api/dto"

func bindingResponse(value Binding) dto.WorkflowBindingResponse {
	response := dto.WorkflowBindingResponse{
		ID:              value.ID,
		PlanID:          value.PlanID,
		PlanDisplayName: value.PlanDisplayName,
		Key:             value.Key,
		DisplayName:     value.DisplayName,
		DescriptionMD:   value.DescriptionMD,
		State:           string(value.State),
		Revision:        value.Revision,
		Owner: dto.WorkflowBindingOwnerResponse{
			UserID: value.Owner.UserID, MemberID: value.Owner.MemberID,
		},
		CreatedBy:  actorResponse(value.CreatedBy),
		CreatedAt:  value.CreatedAt,
		UpdatedBy:  actorResponse(value.UpdatedBy),
		UpdatedAt:  value.UpdatedAt,
		ArchivedAt: value.ArchivedAt,
	}
	if value.LatestRevision != nil {
		response.LatestRevision = &dto.WorkflowBindingRevisionRefResponse{ID: value.LatestRevision.ID, Revision: value.LatestRevision.Revision}
	}
	if value.ActiveRevision != nil {
		response.ActiveRevision = &dto.WorkflowBindingRevisionRefResponse{ID: value.ActiveRevision.ID, Revision: value.ActiveRevision.Revision}
	}
	if value.ArchivedBy != nil {
		actor := actorResponse(*value.ArchivedBy)
		response.ArchivedBy = &actor
	}
	return response
}

func revisionResponse(value Revision) dto.WorkflowBindingRevisionResponse {
	return dto.WorkflowBindingRevisionResponse{
		ID:            value.ID,
		BindingID:     value.BindingID,
		PlanID:        value.PlanID,
		Revision:      value.Revision,
		PlanVersionID: value.PlanVersionID,
		Source:        nonNilJSON(value.Source),
		InputPolicy:   nonNilJSON(value.InputPolicy),
		Digest:        value.Digest,
		CreatedBy:     actorResponse(value.CreatedBy),
		CreatedAt:     value.CreatedAt,
	}
}

func validationResponse(value Validation) dto.WorkflowBindingValidationResponse {
	return dto.WorkflowBindingValidationResponse{Diagnostics: diagnosticResponses(value.Diagnostics), Digest: value.Digest}
}

func diagnosticResponses(values []Diagnostic) []dto.WorkflowBindingDiagnosticResponse {
	diagnostics := make([]dto.WorkflowBindingDiagnosticResponse, 0, len(values))
	for _, diagnostic := range values {
		diagnostics = append(diagnostics, dto.WorkflowBindingDiagnosticResponse{
			Severity: diagnostic.Severity,
			Code:     diagnostic.Code,
			Path:     diagnostic.Path,
			Message:  diagnostic.Message,
		})
	}
	return diagnostics
}

func actorResponse(value Actor) dto.WorkflowBindingActorResponse {
	return dto.WorkflowBindingActorResponse{Type: value.Type, ID: value.ID, MemberID: value.MemberID}
}

func nonNilJSON(value []byte) []byte {
	if len(value) == 0 {
		return []byte("{}")
	}
	return value
}
