package user

import (
	"context"

	"github.com/rede5/gohorsejobs/backend/internal/core/dto"
	"github.com/rede5/gohorsejobs/backend/internal/core/ports"
	apidto "github.com/rede5/gohorsejobs/backend/internal/dto"
)

type ListUsersUseCase struct {
	userRepo ports.UserRepository
}

func NewListUsersUseCase(uRepo ports.UserRepository) *ListUsersUseCase {
	return &ListUsersUseCase{
		userRepo: uRepo,
	}
}

func (uc *ListUsersUseCase) Execute(ctx context.Context, tenantID string, page, limit int) (*apidto.PaginatedResponse, error) {
	if page <= 0 {
		page = 1
	}
	if limit <= 0 {
		limit = 10
	}
	if limit > 100 {
		limit = 100
	}
	offset := (page - 1) * limit
	if offset < 0 {
		offset = 0
	}

	users, total, err := uc.userRepo.FindAllByTenant(ctx, tenantID, limit, offset)
	if err != nil {
		return nil, err
	}

	response := []dto.UserResponse{}
	for _, u := range users {
		roles := make([]string, len(u.Roles))
		for i, r := range u.Roles {
			roles[i] = r.Name
		}

		response = append(response, dto.UserResponse{
			ID:        u.ID,
			Name:      u.Name,
			Email:     u.Email,
			Roles:     roles,
			Status:    u.Status,
			CreatedAt: u.CreatedAt,
		})
	}

	return &apidto.PaginatedResponse{
		Data: response,
		Pagination: apidto.Pagination{
			Page:  page,
			Limit: limit,
			Total: total,
		},
	}, nil
}
