import axios from 'axios';

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

// Response interceptor: Backend wraps responses as { success, data }.
// Auto-extract the inner `data` so consumers can use `res.data` directly
// without needing `res.data?.data ?? res.data?.characters ?? res.data` chains.
api.interceptors.response.use((response) => {
  if (
    response.data &&
    typeof response.data === 'object' &&
    !Array.isArray(response.data) &&
    'data' in response.data
  ) {
    response.data = response.data.data;
  }
  return response;
});

// ── Characters ──

export const characters = {
  list: () => api.get('/characters'),
  get: (id: string) => api.get(`/characters/${id}`),
  create: (data: Record<string, unknown>) => api.post('/characters', data),
  update: (id: string, data: Record<string, unknown>) => api.put(`/characters/${id}`, data),
  delete: (id: string) => api.delete(`/characters/${id}`),
  clone: (id: string, data?: Record<string, unknown>) => api.post(`/characters/${id}/clone`, data),
  activate: (id: string) => api.post(`/characters/${id}/activate`),
  deactivate: (id: string) => api.post(`/characters/${id}/deactivate`),
  getConversationProfile: (id: string) => api.get(`/characters/${id}/conversation-profile`),
  updateConversationProfile: (id: string, data: Record<string, unknown>) =>
    api.put(`/characters/${id}/conversation-profile`, data),
  getReferenceImages: (id: string) => api.get(`/characters/${id}/reference-images`),
  regenerateReferenceImages: (id: string) => api.post(`/characters/${id}/reference-images`),
  getApiCredentials: (id: string) => api.get(`/characters/${id}/api-credentials`),
  updateApiCredentials: (id: string, data: { telegramApiId: number; telegramApiHash: string }) =>
    api.put(`/characters/${id}/api-credentials`, data),
};

// ── Conversations ──

export const conversations = {
  list: (characterId: string) => api.get(`/characters/${characterId}/conversations`),
  getHistory: (characterId: string, userId: string) =>
    api.get(`/characters/${characterId}/conversations/${userId}`),
  deleteHistory: (characterId: string, userId: string) =>
    api.delete(`/characters/${characterId}/conversations/${userId}`),
  getMessages: (characterId: string, userId: string, params?: { page?: number; limit?: number }) =>
    api.get(`/characters/${characterId}/conversations/${userId}/messages`, { params }),
};

// ── Images ──

export const images = {
  generate: (characterId: string, data: Record<string, unknown>) =>
    api.post(`/characters/${characterId}/images/generate`, data),
  list: (characterId: string) => api.get(`/characters/${characterId}/images`),
  getDetail: (characterId: string, imageId: string) =>
    api.get(`/characters/${characterId}/images/${imageId}`),
  delete: (characterId: string, imageId: string) =>
    api.delete(`/characters/${characterId}/images/${imageId}`),
};


// ── Templates ──

export const templates = {
  list: (params?: { category?: string; q?: string }) => api.get('/templates', { params }),
  get: (id: string) => api.get(`/templates/${id}`),
  create: (data: Record<string, unknown>) => api.post('/templates', data),
  update: (id: string, data: Record<string, unknown>) => api.put(`/templates/${id}`, data),
  delete: (id: string) => api.delete(`/templates/${id}`),
  getCategories: () => api.get('/templates/categories'),
  personalize: (id: string, characterId: string) =>
    api.post(`/templates/${id}/personalize`, { characterId }),
};

// ── Stars ──

export const stars = {
  getStats: (characterId: string, period?: string) =>
    api.get(`/characters/${characterId}/stars`, { params: period ? { period } : undefined }),
  getTransactions: (characterId: string, params?: Record<string, string>) =>
    api.get(`/characters/${characterId}/stars/transactions`, { params }),
};

// ── Channels ──

export const channels = {
  create: (characterId: string, data?: Record<string, unknown>) =>
    api.post(`/characters/${characterId}/channels`, data),
  get: (characterId: string) => api.get(`/characters/${characterId}/channels`),
  updateSettings: (characterId: string, channelType: string, data: Record<string, unknown>) =>
    api.put(`/characters/${characterId}/channels/${channelType}`, data),
  publish: (characterId: string, channelType: string, data?: Record<string, unknown>) =>
    api.post(`/characters/${characterId}/channels/${channelType}/publish`, data),
};

// ── Analytics ──

export const analytics = {
  getCharacterAnalytics: (characterId: string, params?: Record<string, string>) =>
    api.get(`/analytics/characters/${characterId}`, { params }),
  getComparison: () => api.get('/analytics/comparison'),
  getOverview: () => api.get('/analytics/overview'),
};

// ── Queue ──

export const queue = {
  getStatus: () => api.get('/queue/status'),
  getFailed: () => api.get('/queue/failed'),
  retryFailed: (id: string) => api.post(`/queue/failed/${id}/retry`),
};

// ── System ──

export const system = {
  health: () => api.get('/system/health'),
  errors: () => api.get('/system/errors'),
  getApiConfig: () => api.get('/system/api-config'),
  updateApiConfig: (data: Record<string, unknown>) => api.put('/system/api-config', data),
  testApiKey: (provider: string) => api.post('/system/test-api-key', { provider }),
};

// ── Backup ──

export const backup = {
  create: () => api.post('/backup'),
  list: () => api.get('/backup/list'),
  restore: (data: FormData) =>
    api.post('/backup/restore', data, {
      headers: { 'Content-Type': 'multipart/form-data' },
    }),
  getStatus: () => api.get('/backup/status'),
};

// ── Translation ──

export const translation = {
  translate: (data: Record<string, unknown>) => api.post('/translate', data),
  getGlossary: () => api.get('/translate/glossary'),
  updateGlossary: (data: Record<string, unknown>) => api.put('/translate/glossary', data),
};


// ── Userbot ──

export const userbot = {
  startLogin: (data: { characterId: string; phoneNumber: string }) =>
    api.post('/userbot/login/start', data),
  verifyLogin: (data: { characterId: string; code?: string; password?: string }) =>
    api.post('/userbot/login/verify', data),
  logout: (data: { characterId: string }) =>
    api.post('/userbot/logout', data),
  getSessions: () => api.get('/userbot/sessions'),
  getStatus: (characterId: string) => api.get(`/userbot/status/${characterId}`),
};

// ── Notifications ──

export const notifications = {
  list: (params?: { limit?: number; unreadOnly?: boolean }) =>
    api.get('/notifications', { params }),
  getUnreadCount: () => api.get('/notifications/unread-count'),
  markAsRead: (id: string) => api.put(`/notifications/${id}/read`),
  markAllAsRead: () => api.put('/notifications/read-all'),
};

// ── Telegram Management ──

export const telegramManagement = {
  createGroup: (characterId: string, data: Record<string, unknown>) =>
    api.post(`/characters/${characterId}/telegram/groups`, data),
  createChannel: (characterId: string, data: Record<string, unknown>) =>
    api.post(`/characters/${characterId}/telegram/channels`, data),
  listEntities: (characterId: string) =>
    api.get(`/characters/${characterId}/telegram/entities`),
  updateEntity: (characterId: string, entityId: string, data: Record<string, unknown>) =>
    api.put(`/characters/${characterId}/telegram/entities/${entityId}`, data),
  getMembers: (characterId: string, entityId: string) =>
    api.get(`/characters/${characterId}/telegram/entities/${entityId}/members`),
  publishContent: (characterId: string, entityId: string, data: Record<string, unknown>) =>
    api.post(`/characters/${characterId}/telegram/entities/${entityId}/publish`, data),
  getStarGifts: (characterId: string) =>
    api.get(`/characters/${characterId}/telegram/gifts`),
  sendGift: (characterId: string, data: { giftId: string; recipientId?: string; recipientUsername?: string; message?: string }) =>
    api.post(`/characters/${characterId}/telegram/gifts/send`, data),
};



export default api;