package service

import (
	"context"

	"git.itzana.me/strafesnet/maps-service/pkg/api"
)

// GetOperation implements getOperation operation.
//
// Get the specified operation by ID.
//
// GET /operations/{OperationID}
func (svc *Service) GetOperation(ctx context.Context, params api.GetOperationParams) (*api.Operation, error) {
	userInfo, ok := ctx.Value("UserInfo").(UserInfoHandle)
	if !ok {
		return nil, ErrUserInfo
	}

	// You must be the operation owner to read it

	operation, err := svc.DB.Operations().Get(ctx, params.OperationID)
	if err != nil {
		return nil, err
	}

	userId, err := userInfo.GetUserID()
	if err != nil {
		return nil, err
	}

	// check if caller is the submitter
	has_role := userId == operation.Owner
	if !has_role {
		return nil, ErrPermissionDeniedNotSubmitter
	}

	return &api.Operation{
		OperationID:   operation.ID,
		Date:          operation.CreatedAt.Unix(),
		Owner:         int64(operation.Owner),
		Status:        int32(operation.StatusID),
		StatusMessage: operation.StatusMessage,
		Path:          operation.Path,
	}, nil
}