package mappers

import (
	"apskel-pos-be/internal/constants"
	"apskel-pos-be/internal/entities"
	"apskel-pos-be/internal/models"
)

func UserEntityToModel(entity *entities.User) *models.User {
	if entity == nil {
		return nil
	}

	return &models.User{
		ID:             entity.ID,
		OrganizationID: entity.OrganizationID,
		OutletID:       entity.OutletID,
		Name:           entity.Name,
		Email:          entity.Email,
		Role:           constants.UserRole(entity.Role),
		Permissions:    map[string]interface{}(entity.Permissions),
		IsActive:       entity.IsActive,
		CreatedAt:      entity.CreatedAt,
		UpdatedAt:      entity.UpdatedAt,
	}
}

func UserModelToEntity(model *models.User) *entities.User {
	if model == nil {
		return nil
	}

	return &entities.User{
		ID:             model.ID,
		OrganizationID: model.OrganizationID,
		OutletID:       model.OutletID,
		Name:           model.Name,
		Email:          model.Email,
		Role:           entities.UserRole(model.Role),
		Permissions:    entities.Permissions(model.Permissions),
		IsActive:       model.IsActive,
		CreatedAt:      model.CreatedAt,
		UpdatedAt:      model.UpdatedAt,
	}
}

func UserCreateRequestToEntity(req *models.CreateUserRequest, passwordHash string) *entities.User {
	if req == nil {
		return nil
	}

	permissions := entities.Permissions{}
	if req.Permissions != nil {
		permissions = entities.Permissions(req.Permissions)
	}

	return &entities.User{
		OrganizationID: req.OrganizationID,
		OutletID:       req.OutletID,
		Name:           req.Name,
		Email:          req.Email,
		PasswordHash:   passwordHash,
		Role:           entities.UserRole(req.Role),
		Permissions:    permissions,
		IsActive:       true,
	}
}

func UserEntityToResponse(entity *entities.User) *models.UserResponse {
	if entity == nil {
		return nil
	}

	return &models.UserResponse{
		ID:             entity.ID,
		OrganizationID: entity.OrganizationID,
		OutletID:       entity.OutletID,
		Name:           entity.Name,
		Email:          entity.Email,
		Role:           constants.UserRole(entity.Role),
		Permissions:    map[string]interface{}(entity.Permissions),
		IsActive:       entity.IsActive,
		CreatedAt:      entity.CreatedAt,
		UpdatedAt:      entity.UpdatedAt,
	}
}

func UserEntitiesToModels(entities []*entities.User) []*models.User {
	if entities == nil {
		return nil
	}

	models := make([]*models.User, len(entities))
	for i, entity := range entities {
		models[i] = UserEntityToModel(entity)
	}
	return models
}

func UserEntitiesToResponses(entities []*entities.User) []*models.UserResponse {
	if entities == nil {
		return nil
	}

	responses := make([]*models.UserResponse, len(entities))
	for i, entity := range entities {
		responses[i] = UserEntityToResponse(entity)
	}
	return responses
}
