import axios, { AxiosInstance } from 'axios';
import type {
  LoginRequest,
  LoginResponse,
  RegisterRequest,
  RegisterResponse,
  LogoutResponse,
  ProfileResponse,
  UpdateProfileRequest,
  ChangePasswordRequest,
} from '../model/types';

// Use Next.js API proxy to bypass CORS issues
const USER_API_BASE = '/api/v1/users';

const userApiClient: AxiosInstance = axios.create({
  baseURL: USER_API_BASE,
  timeout: 90000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request interceptor
userApiClient.interceptors.request.use(
  (config) => {
    console.log('👤 User API Request:', {
      method: config.method?.toUpperCase(),
      url: config.url,
      baseURL: config.baseURL,
    });

    const token = localStorage.getItem('accessToken');
    if (token && config.headers) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.error('❌ User API Request Error:', error);
    return Promise.reject(error);
  }
);

// Response interceptor
userApiClient.interceptors.response.use(
  (response) => {
    console.log('✅ User API Response:', {
      status: response.status,
      url: response.config.url,
    });
    return response;
  },
  (error) => {
    console.error('❌ User API Error:', {
      message: error.message,
      status: error.response?.status,
      url: error.config?.url,
    });
    return Promise.reject(error);
  }
);

/**
 * User API Service
 * 사용자 인증 및 프로필 관리 API
 */
export const userApi = {
  /**
   * 로그인
   */
  login: async (data: LoginRequest): Promise<LoginResponse> => {
    const response = await userApiClient.post<LoginResponse>(
      '/login',
      data
    );
    return response.data;
  },

  /**
   * 회원가입
   */
  register: async (data: RegisterRequest): Promise<RegisterResponse> => {
    console.log('📞 userApi.register 호출');
    console.log('📦 요청 데이터:', {
      ...data,
      password: '***'
    });

    try {
      const response = await userApiClient.post<RegisterResponse>(
        '/register',
        data
      );
      console.log('✅ userApi.register 성공:', response.data);
      return response.data;
    } catch (error) {
      console.error('❌ userApi.register 실패:', error);
      throw error;
    }
  },

  /**
   * 로그아웃
   */
  logout: async (): Promise<LogoutResponse> => {
    const response = await userApiClient.post<LogoutResponse>(
      '/logout',
      {}
    );
    return response.data;
  },

  /**
   * 프로필 조회
   */
  getProfile: async (): Promise<ProfileResponse> => {
    const response = await userApiClient.get<ProfileResponse>(
      '/profile'
    );
    return response.data;
  },

  /**
   * 프로필 수정
   */
  updateProfile: async (
    data: UpdateProfileRequest
  ): Promise<ProfileResponse> => {
    const response = await userApiClient.put<ProfileResponse>(
      '/profile',
      data
    );
    return response.data;
  },

  /**
   * 비밀번호 변경
   */
  changePassword: async (data: ChangePasswordRequest): Promise<void> => {
    await userApiClient.put('/password', data);
  },
};

export default userApi;
