import axios from 'axios';
import { API_BASE_URL } from './apiConfig';

const authApi = axios.create({
  baseURL: `${API_BASE_URL}/auth`,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

export interface SignUpRequest {
  username: string;
  email: string;
  password: string;
  name?: string;
}

export interface LoginRequest {
  usernameOrEmail: string;
  password: string;
}

export interface AuthResponse {
  accessToken: string;
  tokenType: string;
  userId: number;
  username: string;
  email: string;
  name?: string;
}

export interface UserResponse {
  id: number;
  username: string;
  email: string;
  name?: string;
  role: string;
  createdAt: string;
  lastLoginAt?: string;
}

export const authService = {
  /**
   * 회원가입
   */
  async signUp(request: SignUpRequest): Promise<AuthResponse> {
    const response = await authApi.post<AuthResponse>('/signup', request);
    return response.data;
  },

  /**
   * 로그인
   */
  async login(request: LoginRequest): Promise<AuthResponse> {
    const response = await authApi.post<AuthResponse>('/login', request);
    return response.data;
  },

  /**
   * 로그아웃
   */
  async logout(): Promise<void> {
    try {
      await authApi.post('/logout');
    } catch (error) {
      console.log('로그아웃 요청 실패 (서버 측 처리 없음)');
    }
  },

  /**
   * 현재 로그인된 사용자 정보 조회
   */
  async getCurrentUser(token: string): Promise<UserResponse> {
    const response = await authApi.get<UserResponse>('/me', {
      headers: {
        'Authorization': `Bearer ${token}`,
      },
    });
    return response.data;
  },
};

export default authService;

