<%#
 Copyright 2013-2024 the original author or authors from the JHipster project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      https://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= packageName %>.web.rest;
<%_
const pageName = ormTool !== 'mybatis' ? 'Page': 'IPage';
const pageGetContent = ormTool !== 'mybatis' ? 'getContent': 'getRecords';
const pageUtil = ormTool !== 'mybatis' ? 'PaginationUtil': 'IPageUtil';
const pageInstance = ormTool !== 'mybatis' ? 'pageable' : 'PageableUtils.toPage(pageable)';
_%>
<%_ if (searchEngineElasticsearch) { _%>
import <%= packageName %>.repository.search.UserSearchRepository;
<%_ } else if (searchEngineCouchbase) { _%>
import <%= packageName %>.repository.UserRepository;
import <%= packageName %>.domain.User;
  <%_ if (!reactive) { _%>
import java.util.stream.StreamSupport;
  <%_ } _%>
<%_ } _%>
<%_ if (!authenticationTypeOauth2) { _%>
import org.springframework.data.domain.Sort;
import java.util.Collections;
<%_ } _%>
import <%= packageName %>.service.UserService;
import <%= packageName %>.service.criteria.UserCriteria;
import <%= packageName %>.service.UserQueryService;
import <%= packageName %>.service.dto.<%= user.dtoClass %>;

<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%>
  <%_ if (ormTool === 'hibernate') { _%>
import tech.jhipster.web.util.PaginationUtil;
  <%_ } else { _%>
import <%= packageName %>.util.web.IPageUtil;
import <%= packageName %>.util.web.PageableUtils;
  <%_ } _%>
<%_ } _%>

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%>
  <%_ if (reactive) { _%>
import org.springframework.data.domain.PageImpl;
  <%_ } else { _%>
    <%_ if (ormTool === 'hibernate') { _%>
import org.springframework.data.domain.Page;
    <%_ } else { _%>
import com.baomidou.mybatisplus.core.metadata.IPage;
    <%_ } _%>
  <%_ } _%>
import org.springframework.data.domain.Pageable;
import <%= packageName %>.service.mapper.UserMapper;
  <%_ if (!reactive) { _%>
import org.springframework.http.HttpHeaders;
  <%_ } _%>
<%_ } _%>
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
<%_ if (reactive) { _%>
import org.springframework.http.server.reactive.ServerHttpRequest;
<%_ } _%>
import org.springframework.web.bind.annotation.*;
<%_ if (reactive) { _%>
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.util.ForwardedHeaderUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
<%_ } else {_%>
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
<%_ } _%>

import java.util.*;
<%_ if (searchEngineElasticsearch && !reactive) { _%>
import java.util.stream.StreamSupport;
<%_ } _%>

@RestController
@RequestMapping("/api")
public class PublicUserResource {
<%_ if (!authenticationTypeOauth2) { _%>
    private static final List<String> ALLOWED_ORDERED_PROPERTIES = Collections.unmodifiableList(Arrays.asList("id", "login", "firstName", "lastName", "email", "activated", "langKey"));
<%_ } _%>

    private static final Logger log = LoggerFactory.getLogger(PublicUserResource.class);

    private final UserService userService;

    private final UserQueryService userQueryService;

    private final UserMapper userMapper;

<%_ if (searchEngineElasticsearch) { _%>
    private final UserSearchRepository userSearchRepository;
<%_ } else if (searchEngineCouchbase) { _%>
    private final UserRepository userRepository;
<%_ } _%>

    public PublicUserResource(
<%_ if (searchEngineElasticsearch) { -%>
        UserSearchRepository userSearchRepository,
<%_ } else if (searchEngineCouchbase) { -%>
        UserRepository userRepository,
<%_ } -%>
        UserService userService,
        UserQueryService userQueryService,
        UserMapper userMapper
    ) {
        this.userService = userService;
        this.userQueryService = userQueryService;
        this.userMapper = userMapper;
<%_ if (searchEngineElasticsearch) { _%>
        this.userSearchRepository = userSearchRepository;
<%_ } else if (searchEngineAny) { _%>
        this.userRepository = userRepository;
<%_ } _%>
    }

    /**
     * {@code GET /users} : get all users with only public information - calling this method is allowed for anyone.
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%>
     *
  <%_ if (reactive) { _%>
     * @param request a {@link ServerHttpRequest} request.
  <%_ } _%>
     * @param pageable the pagination information.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users.
<%_ } _%>
     */
    @GetMapping("/users")
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%>
  <%_ if (reactive) { _%>
    public Mono<ResponseEntity<Flux<<%= user.dtoClass %>>>> getAllPublicUsers(ServerHttpRequest request, @org.springdoc.core.annotations.ParameterObject Pageable pageable) {
        log.debug("REST request to get all public User names");
    <%_ if (!authenticationTypeOauth2) { _%>
        if (!onlyContainsAllowedProperties(pageable)) {
            return Mono.just(ResponseEntity.badRequest().build());
        }
    <%_ } _%>

        return userService.countManagedUsers()
            .map(total -> new PageImpl<>(new ArrayList<>(), pageable, total))
            .map(page -> PaginationUtil.generatePaginationHttpHeaders(ForwardedHeaderUtils.adaptFromForwardedHeaders(request.getURI(), request.getHeaders()), page))
            .map(headers -> ResponseEntity.ok().headers(headers).body(userService.getAllPublicUsers(pageable)));
    }
  <%_ } else { _%>
    public ResponseEntity<List<<%= user.dtoClass %>>> getAllPublicUsers(@org.springdoc.<%= javaVersion === '17' ? 'core' : 'api'%>.annotations.ParameterObject Pageable pageable, UserCriteria criteria) {
        log.debug("REST request to get all public User names");
    <%_ if (!authenticationTypeOauth2 && ormTool !== 'mybatis') { _%>
        if (!onlyContainsAllowedProperties(pageable)) {
            return ResponseEntity.badRequest().build();
        }
    <%_ } _%>

        // final Page<<%= user.dtoClass %>> page = userService.getAllPublicUsers(pageable);
        final <%= pageName%><<%= user.dtoClass %>> page = userQueryService.findByCriteria(criteria, <%= pageInstance%>);
        HttpHeaders headers = <%= pageUtil%>.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return new ResponseEntity<>(page.<%= pageGetContent%>(), headers, HttpStatus.OK);
    }
  <%_ } _%>
  <%_ if (!authenticationTypeOauth2) { _%>
    private boolean onlyContainsAllowedProperties(Pageable pageable) {
        return pageable.getSort().stream().map(Sort.Order::getProperty).allMatch(ALLOWED_ORDERED_PROPERTIES::contains);
    }
  <%_ } _%>

<%_ } else { /* Cassandra */ _%>
    public <% if (reactive) { %>Flux<% } else { %>List<% } %><<%= user.dtoClass %>> getAllPublicUsers() {
        return userService.getAllPublicUsers();
    }

<%_ } _%>
    /**
     * {@code GET /users/check} : check user exist.
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%>
     *
  <%_ if (reactive) { _%>
     * @param request a {@link ServerHttpRequest} request.
  <%_ } _%>
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users.
<%_ } _%>
     */
    @GetMapping("/users/check")
<%_ if (databaseTypeSql || databaseTypeMongodb || databaseTypeNeo4j || databaseTypeCouchbase) { _%>
  <%_ if (reactive) { _%>
    public Mono<ResponseEntity<Boolean>> existUser(ServerHttpRequest request, UserCriteria criteria) {
        log.debug("REST request to get all public User names");

        if (criteria == null) {
            return ResponseEntity.ok(false);
        }
        UserCriteria newCriteria = new UserCriteria();
        newCriteria.setLogin(criteria.getLogin());
        newCriteria.setMobile(criteria.getMobile());
        newCriteria.setEmail(criteria.getEmail());
        newCriteria.setId(criteria.getId());
        long count = userQueryService.countByCriteria(newCriteria);
        return ResponseEntity.ok(count > 0);
    }
  <%_ } else { _%>
    public ResponseEntity<Boolean> existUser(UserCriteria criteria) {
        log.debug("REST request to get all public User names");
        if (criteria == null) {
            return ResponseEntity.ok(false);
        }
        UserCriteria newCriteria = new UserCriteria();
        newCriteria.setLogin(criteria.getLogin());
        newCriteria.setMobile(criteria.getMobile());
        newCriteria.setEmail(criteria.getEmail());
        newCriteria.setId(criteria.getId());
        long count = userQueryService.countByCriteria(newCriteria);
        return ResponseEntity.ok(count > 0);
    }
  <%_ } _%>
<%_ } _%>

<%_ if (searchEngineAny) { _%>

    /**
     * {@code SEARCH /users/_search/:query} : search for the User corresponding to the query.
     *
     * @param query the query to search.
     * @return the result of the search.
     */
    @GetMapping("/users/_search/{query}")
    public <% if(reactive) { %>Mono<<% } %>List<<%= user.dtoClass %>><% if(reactive) { %>><% } %> search(@PathVariable("query") String query) {
  <%_ if (searchEngineElasticsearch) { _%>
    <%_ if (reactive) { _%>
        return userSearchRepository.search(query).map(<%= user.dtoClass %>::new).collectList();
    <%_ } else { _%>
        return StreamSupport
            .stream(userSearchRepository.search(query).spliterator(), false)
            .map(userMapper::toDto)
            .toList();
    <%_ } _%>
  <%_ } else { _%>
     <%_ if (reactive) { _%>
        return userRepository.search(query).map(<%= user.dtoClass %>::new).collectList();
     <%_ } else { _%>
        return StreamSupport
            .stream(userRepository.search(query).spliterator(), false)
            .map(userMapper::toDto)
            .toList();
     <%_ } _%>
  <%_ } _%>
    }
<%_ } _%>

}
