package services

import (
	"errors"

	"github.com/treytartt/honeydue-api/internal/apperrors"
	"github.com/treytartt/honeydue-api/internal/dto/responses"
	"github.com/treytartt/honeydue-api/internal/repositories"
)

var (
	// Deprecated: Use apperrors.NotFound("error.user_not_found") instead
	ErrUserNotFound = errors.New("user not found")
)

// UserService handles user-related business logic
type UserService struct {
	userRepo *repositories.UserRepository
}

// NewUserService creates a new user service
func NewUserService(userRepo *repositories.UserRepository) *UserService {
	return &UserService{
		userRepo: userRepo,
	}
}

// ListUsersInSharedResidences returns users that share residences with the given user
func (s *UserService) ListUsersInSharedResidences(userID uint) ([]responses.UserSummary, error) {
	users, err := s.userRepo.FindUsersInSharedResidences(userID)
	if err != nil {
		return nil, apperrors.Internal(err)
	}

	// F-23: Initialize as empty slice so JSON serialization produces [] instead of null
	result := make([]responses.UserSummary, 0, len(users))
	for _, u := range users {
		result = append(result, responses.UserSummary{
			ID:        u.ID,
			Username:  u.Username,
			Email:     u.Email,
			FirstName: u.FirstName,
			LastName:  u.LastName,
		})
	}

	return result, nil
}

// GetUserIfSharedResidence returns a user if they share a residence with the requesting user
func (s *UserService) GetUserIfSharedResidence(targetUserID, requestingUserID uint) (*responses.UserSummary, error) {
	user, err := s.userRepo.FindUserIfSharedResidence(targetUserID, requestingUserID)
	if err != nil {
		return nil, apperrors.Internal(err)
	}
	if user == nil {
		return nil, apperrors.NotFound("error.user_not_found")
	}

	return &responses.UserSummary{
		ID:        user.ID,
		Username:  user.Username,
		Email:     user.Email,
		FirstName: user.FirstName,
		LastName:  user.LastName,
	}, nil
}

// ListProfilesInSharedResidences returns user profiles for users in shared residences
func (s *UserService) ListProfilesInSharedResidences(userID uint) ([]responses.UserProfileSummary, error) {
	profiles, err := s.userRepo.FindProfilesInSharedResidences(userID)
	if err != nil {
		return nil, apperrors.Internal(err)
	}

	// F-23: Initialize as empty slice so JSON serialization produces [] instead of null
	result := make([]responses.UserProfileSummary, 0, len(profiles))
	for _, p := range profiles {
		result = append(result, responses.UserProfileSummary{
			ID:             p.ID,
			UserID:         p.UserID,
			Bio:            p.Bio,
			ProfilePicture: p.ProfilePicture,
			PhoneNumber:    p.PhoneNumber,
		})
	}

	return result, nil
}
