package service

import (
	"bitbucket.org/nemt/nemt-portal-api/domain/entity"
	"bitbucket.org/nemt/nemt-portal-api/infra/errors"
)

// userService is the domain service for user operations
type visitService struct {
	svc *Service
}

// newUserService returns an instance of userService
func newVisitService(svc *Service) *visitService {
	return &visitService{
		svc: svc,
	}
}

// Save the ride for a expected user
func (s *visitService) Create(visit entity.Visit) (entity.Visit, error) {
	return s.svc.db.Visits().Create(visit)
}

// Save the ride for a expected user
func (s *visitService) GetAll(user entity.User) ([]entity.Visit, error) {
	visit, err := s.svc.db.Visits().GetAll(user)
	if err != nil {
		return nil, err
	}

	rides, _ := s.svc.db.Rides().GetAll(user)
	// if err != nil {
	// 	return nil, err
	// }

	ridesByVisit := make(map[int64][]entity.Ride)
	for _, r := range rides {
		rides := ridesByVisit[r.Visit.ID]
		rides = append(rides, r)
		ridesByVisit[r.Visit.ID] = rides
	}

	for i, v := range visit {
		visit[i].Rides = ridesByVisit[v.ID]
	}

	return visit, nil
}

// Save the ride for a expected user
func (s *visitService) GetByUUID(visitUUID string, user entity.User) (entity.Visit, error) {
	visit, err := s.svc.db.Visits().GetByUUID(visitUUID, user)
	if err != nil {
		return entity.Visit{}, errors.Wrap(err)
	}

	rides, _ := s.svc.db.Rides().GetByVisitUUID(visitUUID, user)
	// if err != nil {
	// 	return entity.Visit{}, errors.Wrap(err)
	// }
	visit.Rides = rides

	return visit, nil
}

// Save the ride for a expected user
func (s *visitService) GetByID(visitID int64, user entity.User) (entity.Visit, error) {
	visit, err := s.svc.db.Visits().GetByID(visitID, user)
	if err != nil {
		return entity.Visit{}, errors.Wrap(err)
	}

	rides, _ := s.svc.db.Rides().GetByVisitUUID(visit.UUID, user)
	// if err != nil {
	// 	return entity.Visit{}, errors.Wrap(err)
	// }
	visit.Rides = rides

	return visit, nil
}
