package com.kamco.cd.training.members.service;

import com.kamco.cd.training.common.enums.error.AuthErrorCode;
import com.kamco.cd.training.common.exception.CustomApiException;
import com.kamco.cd.training.members.dto.SignInRequest;
import com.kamco.cd.training.postgres.core.MembersCoreService;
import com.kamco.cd.training.postgres.core.TokenCoreService;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class AuthService {

  private final MembersCoreService membersCoreService;
  private final TokenCoreService tokenCoreService;

  /**
   * 토큰 저장
   *
   * @param subject
   * @param refreshToken
   * @param validityMs
   */
  @Transactional
  public void tokenSave(String subject, String refreshToken, long validityMs) {
    tokenCoreService.save(subject, refreshToken, validityMs);
  }

  /**
   * refreshToken을 DB와 비교 검증
   *
   * @param subject 사용자 식별(UUID)
   * @param requestRefreshToken refresh token
   */
  public void validateRefreshToken(String subject, String requestRefreshToken) {
    String savedToken = tokenCoreService.getValidTokenOrThrow(subject);

    if (!savedToken.equals(requestRefreshToken)) {
      throw new CustomApiException(AuthErrorCode.REFRESH_TOKEN_MISMATCH);
    }
  }

  /**
   * 로그아웃(토큰폐기)
   *
   * @param subject 사용자 식별(UUID)
   */
  @Transactional
  public void logout(String subject) {
    // RefreshToken 폐기
    tokenCoreService.revokeBySubject(subject);
  }

  /**
   * 로그인 일시 저장
   *
   * @param uuid
   */
  @Transactional
  public void saveLogin(UUID uuid) {
    membersCoreService.saveLogin(uuid);
  }

  /**
   * 사용자 상태 조회
   *
   * @param request
   * @return
   */
  public String getUserStatus(SignInRequest request) {
    return membersCoreService.getUserStatus(request);
  }
}
