package com.ffii.core.common.mobile.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.ffii.core.common.mobile.service.AccessTokenService;
import com.ffii.core.support.AbstractController;

import io.swagger.v3.oas.annotations.Operation;

/** @author Fung */
@RestController
@RequestMapping("/protected/mobile")
public class ProtectedMobileLogoutController extends AbstractController {

  protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

  private final String AUTH_HEADER_DEVICE_ID;
  private final String AUTH_HEADER_ACCESS_TOKEN;
  private AccessTokenService accessTokenService;

  public ProtectedMobileLogoutController(
      @Value("${app.mobile.auth-header.deviceId:X-ATT-DeviceId}") String authHeaderDeviceId,
      @Value("${app.mobile.auth-header.accessToken:X-ATT-Access-Token}") String authHeaderAccessToken,
      AccessTokenService accessTokenService) {
    this.AUTH_HEADER_DEVICE_ID = authHeaderDeviceId;
    this.AUTH_HEADER_ACCESS_TOKEN = authHeaderAccessToken;
    this.accessTokenService = accessTokenService;
  }

  @Operation(summary = "logout current session")
  @PostMapping("/logout")
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public void logout(HttpServletRequest request) {
    String deviceId = request.getHeader(this.AUTH_HEADER_DEVICE_ID);
    String accessToken = request.getHeader(this.AUTH_HEADER_ACCESS_TOKEN);

    if (deviceId != null && accessToken != null) {
      accessTokenService.logout(deviceId, accessToken);
    }
  }

  @Operation(summary = "logout all mobile session")
  @PostMapping("/logout-all")
  @ResponseStatus(HttpStatus.NO_CONTENT)
  public void logoutAll(Authentication Authentication) {
    accessTokenService.logoutAll(Authentication.getName());
  }

}
