import axios from 'axios';
import { isDemoMode } from './demo';

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001/api';

const api = axios.create({
  baseURL: API_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

// Демо-данные
const demoData = {
  user: {
    _id: 'demo_user_id',
    telegramId: '12345',
    username: 'demo_user',
    level: 1,
    experience: 0,
    balance: 1000,
    achievements: [],
  },
  shopItems: [
    {
      _id: 'demo_item_1',
      name: 'Демо предмет 1',
      description: 'Описание демо предмета 1',
      price: 100,
      type: 'consumable',
    },
    {
      _id: 'demo_item_2',
      name: 'Демо предмет 2',
      description: 'Описание демо предмета 2',
      price: 200,
      type: 'permanent',
    },
  ],
};

// Интерцептор для добавления токена
api.interceptors.request.use((config) => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
});

// Интерцептор для обработки ошибок
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token');
    }
    return Promise.reject(error);
  }
);

export const auth = async (telegramId: string, username: string) => {
  if (isDemoMode()) {
    localStorage.setItem('token', 'demo_token');
    return { token: 'demo_token', user: demoData.user };
  }
  
  const response = await api.post('/auth', { telegramId, username });
  const { token } = response.data;
  localStorage.setItem('token', token);
  return response.data;
};

export const getProfile = async () => {
  if (isDemoMode()) {
    return demoData.user;
  }
  
  const response = await api.get('/profile');
  return response.data;
};

export const getShopItems = async () => {
  if (isDemoMode()) {
    return demoData.shopItems;
  }
  
  const response = await api.get('/shop');
  return response.data;
};

export const purchaseItem = async (itemId: string) => {
  if (isDemoMode()) {
    const item = demoData.shopItems.find(item => item._id === itemId);
    if (!item) {
      throw new Error('Предмет не найден');
    }
    if (demoData.user.balance < item.price) {
      throw new Error('Недостаточно средств');
    }
    demoData.user.balance -= item.price;
    return { user: demoData.user };
  }
  
  const response = await api.post(`/shop/purchase/${itemId}`);
  return response.data;
};

export const transferBalance = async (username: string, amount: number) => {
  if (isDemoMode()) {
    if (demoData.user.balance < amount) {
      throw new Error('Недостаточно средств');
    }
    demoData.user.balance -= amount;
    return { balance: demoData.user.balance };
  }
  
  const response = await api.post('/transfer', { username, amount });
  return response.data;
}; 