/*
 * Copyright (c) 2012-2023 Red Hat, Inc.
 * This program and the accompanying materials are made
 * available under the terms of the Eclipse Public License 2.0
 * which is available at https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *   Red Hat, Inc. - initial API and implementation
 */
package org.eclipse.che.api.user.server;

import static jakarta.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED;
import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;
import static jakarta.ws.rs.core.MediaType.TEXT_PLAIN;
import static jakarta.ws.rs.core.Response.Status.CREATED;
import static org.eclipse.che.api.user.server.Constants.LINK_REL_CURRENT_USER;
import static org.eclipse.che.api.user.server.Constants.LINK_REL_CURRENT_USER_PASSWORD;
import static org.eclipse.che.api.user.server.Constants.LINK_REL_USER;
import static org.eclipse.che.api.user.server.DtoConverter.asDto;

import com.google.common.collect.ImmutableMap;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.Consumes;
import jakarta.ws.rs.DELETE;
import jakarta.ws.rs.DefaultValue;
import jakarta.ws.rs.FormParam;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.POST;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.QueryParam;
import jakarta.ws.rs.core.Response;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import org.eclipse.che.api.core.BadRequestException;
import org.eclipse.che.api.core.ConflictException;
import org.eclipse.che.api.core.NotFoundException;
import org.eclipse.che.api.core.ServerException;
import org.eclipse.che.api.core.UnauthorizedException;
import org.eclipse.che.api.core.model.user.User;
import org.eclipse.che.api.core.rest.Service;
import org.eclipse.che.api.core.rest.annotations.GenerateLink;
import org.eclipse.che.api.user.server.model.impl.UserImpl;
import org.eclipse.che.api.user.shared.dto.UserDto;
import org.eclipse.che.commons.env.EnvironmentContext;

/**
 * User REST API.
 *
 * @author Yevhenii Voevodin
 * @author Anton Korneta
 */
@Path("/user")
@Tag(name = "user", description = "User REST API")
public class UserService extends Service {
  public static final String USER_SELF_CREATION_ALLOWED = "che.auth.user_self_creation";

  private final UserManager userManager;
  private final TokenValidator tokenValidator;
  private final UserLinksInjector linksInjector;
  private final UserValidator userValidator;
  private final boolean userSelfCreationAllowed;

  @Inject
  public UserService(
      UserManager userManager,
      TokenValidator tokenValidator,
      UserValidator userNameValidator,
      UserLinksInjector linksInjector,
      @Named(USER_SELF_CREATION_ALLOWED) boolean userSelfCreationAllowed) {
    this.userManager = userManager;
    this.linksInjector = linksInjector;
    this.tokenValidator = tokenValidator;
    this.userValidator = userNameValidator;
    this.userSelfCreationAllowed = userSelfCreationAllowed;
  }

  @GET
  @Path("/id")
  @Produces(TEXT_PLAIN)
  @Operation(
      summary = "Get current user's id",
      responses = {
        @ApiResponse(
            responseCode = "200",
            description =
                "The response contains current user's id ('0000-00-0000' is returned for the anonymous user)"),
      })
  public String getId() {
    return userId();
  }

  @Deprecated
  @POST
  @Consumes(APPLICATION_JSON)
  @Produces(APPLICATION_JSON)
  @GenerateLink(rel = LINK_REL_USER)
  @Operation(
      description = "Create a new user",
      responses = {
        @ApiResponse(
            responseCode = "201",
            description = "User successfully created, response contains created entity",
            content = @Content(schema = @Schema(implementation = UserDto.class))),
        @ApiResponse(
            responseCode = "400",
            description = "Missed required parameters, parameters are not valid"),
        @ApiResponse(responseCode = "401", description = "Missed token parameter"),
        @ApiResponse(
            responseCode = "500",
            description = "Couldn't create user due to internal server error")
      })
  public Response create(
      @Parameter(description = "New user") UserDto userDto,
      @Parameter(description = "Authentication token") @QueryParam("token") String token,
      @Parameter(description = "User type") @QueryParam("temporary") @DefaultValue("false")
          Boolean isTemporary)
      throws BadRequestException, UnauthorizedException, ConflictException, ServerException {
    if (userDto != null) {
      // should be generated by userManager
      userDto.setId(null);
    }
    final User newUser = token == null ? userDto : tokenValidator.validateToken(token);
    userValidator.checkUser(newUser);
    return Response.status(CREATED)
        .entity(
            linksInjector.injectLinks(
                asDto(userManager.create(newUser, isTemporary)), getServiceContext()))
        .build();
  }

  @Deprecated
  @GET
  @Produces(APPLICATION_JSON)
  @GenerateLink(rel = LINK_REL_CURRENT_USER)
  @Operation(
      description = "Get logged in user",
      responses = {
        @ApiResponse(
            responseCode = "200",
            description = "The response contains currently logged in user entity",
            content = @Content(schema = @Schema(implementation = UserDto.class))),
        @ApiResponse(
            responseCode = "500",
            description = "Couldn't get user due to internal server error")
      })
  public UserDto getCurrent() throws NotFoundException, ServerException {
    final User user = userManager.getById(userId());
    return linksInjector.injectLinks(asDto(user), getServiceContext());
  }

  @Deprecated
  @POST
  @Path("/password")
  @Consumes(APPLICATION_FORM_URLENCODED)
  @GenerateLink(rel = LINK_REL_CURRENT_USER_PASSWORD)
  @Operation(
      description =
          "Update password of logged in user. Password must contain at least 8 characters, "
              + "passport must contain letters and digits",
      responses = {
        @ApiResponse(responseCode = "204", description = "Password successfully updated"),
        @ApiResponse(
            responseCode = "500",
            description = "Couldn't update password due to internal server error")
      })
  public void updatePassword(
      @Parameter(description = "New password", required = true) @FormParam("password")
          String password)
      throws NotFoundException, BadRequestException, ServerException, ConflictException {
    userValidator.checkPassword(password);

    final UserImpl user = new UserImpl(userManager.getById(userId()));
    user.setPassword(password);
    userManager.update(user);
  }

  @Deprecated
  @GET
  @Path("/{id}")
  @Produces(APPLICATION_JSON)
  @GenerateLink(rel = LINK_REL_USER)
  @Operation(
      summary = "Get user by identifier",
      responses = {
        @ApiResponse(
            responseCode = "200",
            description = "The response contains requested user entity"),
        @ApiResponse(
            responseCode = "404",
            description = "User with requested identifier not found"),
        @ApiResponse(
            responseCode = "500",
            description = "Impossible to get user due to internal server error")
      })
  public UserDto getById(@Parameter(description = "User identifier") @PathParam("id") String id)
      throws NotFoundException, ServerException {
    final User user = userManager.getById(id);
    return linksInjector.injectLinks(asDto(user), getServiceContext());
  }

  @Deprecated
  @GET
  @Path("/find")
  @Produces(APPLICATION_JSON)
  @GenerateLink(rel = LINK_REL_USER)
  @Operation(
      summary = "Get user by email or name",
      responses = {
        @ApiResponse(
            responseCode = "200",
            description = "The response contains requested user entity"),
        @ApiResponse(
            responseCode = "404",
            description = "User with requested email/name not found"),
        @ApiResponse(
            responseCode = "500",
            description = "Impossible to get user due to internal server error")
      })
  public UserDto find(
      @Parameter(description = "User email, if it is set then name shouldn't be")
          @QueryParam("email")
          String email,
      @Parameter(description = "User name, if is is set then email shouldn't be")
          @QueryParam("name")
          String name)
      throws NotFoundException, ServerException, BadRequestException {
    if (email == null && name == null) {
      throw new BadRequestException("Missed user's email or name");
    }
    if (email != null && name != null) {
      throw new BadRequestException(
          "Expected either user's email or name, while both values received");
    }
    final User user = name == null ? userManager.getByEmail(email) : userManager.getByName(name);
    return linksInjector.injectLinks(asDto(user), getServiceContext());
  }

  @Deprecated
  @DELETE
  @Path("/{id}")
  @GenerateLink(rel = LINK_REL_USER)
  @Operation(
      summary = "Delete user",
      responses = {
        @ApiResponse(responseCode = "204", description = "User successfully removed"),
        @ApiResponse(
            responseCode = "409",
            description = "Couldn't remove user due to conflict(e.g. it has related entities)"),
        @ApiResponse(
            responseCode = "500",
            description = "Couldn't remove user due to internal server error")
      })
  public void remove(@Parameter(description = "User identifier") @PathParam("id") String id)
      throws ServerException, ConflictException {
    userManager.remove(id);
  }

  @Deprecated
  @GET
  @Path("/settings")
  @Produces(APPLICATION_JSON)
  public Map<String, String> getSettings() {
    return ImmutableMap.of(USER_SELF_CREATION_ALLOWED, Boolean.toString(userSelfCreationAllowed));
  }

  private static String userId() {
    return EnvironmentContext.getCurrent().getSubject().getUserId();
  }
}
