/**
 * lib/api.ts — Shim de compatibilidade.
 * Fornece o objeto `api` legado mapeado para os novos endpoints.
 * Migre os consumidores para importar de chatApiService.ts diretamente.
 */
export { api as apiInstance, authApi } from '../services/chatApiService'
import { instanceApi, chatbotApi } from '../services/chatApiService'
import axios from 'axios'

const BASE = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:8008'

const http = axios.create({ baseURL: BASE })
http.interceptors.request.use((cfg) => {
  const t = typeof window !== 'undefined' ? localStorage.getItem('token') : null
  if (t) cfg.headers.Authorization = `Bearer ${t}`
  return cfg
})

/** @deprecated Use authApi from chatApiService.ts */
export const api = {
  // ── Auth ──
  loginUser: async (email: string, password: string) => {
    const { data } = await http.post('/api/auth/login', { email, password })
    return { success: true, token: data.accessToken, refreshToken: data.refreshToken, user: data.user }
  },
  loginAdmin: async (email: string, password: string) => {
    const { data } = await http.post('/api/auth/login', { email, password })
    if (data.user?.role !== 'ADMIN') return { success: false, message: 'Acesso restrito a administradores' }
    return { success: true, token: data.accessToken, refreshToken: data.refreshToken, user: data.user }
  },
  getMe: async () => {
    const { data } = await http.get('/api/auth/me')
    return { success: true, data: { ...data, role: (data.role ?? 'USER').toLowerCase() } }
  },
  register: async (name: string, email: string, password: string) => {
    const { data } = await http.post('/api/auth/register', { name, email, password })
    return { success: true, token: data.accessToken, refreshToken: data.refreshToken, user: data.user }
  },

  // ── Instances ──
  createWhatsAppInstance: (name: string) => instanceApi.create(name),
  getWhatsAppQr: (id: string, _number?: string) => instanceApi.getQr(id),
  disconnectWhatsAppInstance: (id: string) => instanceApi.disconnect(id),
  updateWhatsAppPhoto: async (_name: string) => ({ ok: true }),
  restartWhatsAppInstance: async (id: string) => instanceApi.connect(id),

  getWhatsAppInstances: async () => {
    const data = await instanceApi.list()
    const list = Array.isArray(data) ? data : (data.instances ?? [])
    return {
      instances: list.map((i: any) => ({
        id: i.id,
        instance: i.id,
        nome: i.name,
        status: i.status === 'CONNECTED' ? 'connected' : 'disconnected',
        phone: i.phone ?? '',
      })),
      saved: [],
    }
  },

  // ── Legacy WhatsApp methods (stubs — não existem no novo backend) ──
  getWhatsAppChats: async (instance: string) => {
    const { chatApi } = await import('../services/chatApiService')
    const data = await chatApi.list(instance)
    return { chats: data }
  },
  getWhatsAppContacts: async (_instance: string) => ({ contacts: [] }),
  getWhatsAppHistory: async (phone: string, _limit: number, _skip: number, instance?: string, remoteJid?: string) => {
    const { messageApi } = await import('../services/chatApiService')
    const chatId = remoteJid || phone
    const { messages } = await messageApi.list(chatId)
    return { messages }
  },
  sendWhatsAppText: async (instance: string, to: string, text: string, _leadId?: any, _quotedId?: any, _remoteJid?: any, _quoted?: any) => {
    const { messageApi } = await import('../services/chatApiService')
    return messageApi.send(instance, to, text)
  },
  sendWhatsAppMedia: async (_instance: string, _to: string, _url: string, _type: string, _caption?: string, _leadId?: any) => ({ ok: true }),
  sendWhatsAppAudio: async (_instance: string, _to: string, _url: string, _leadId?: any) => ({ ok: true }),
  editWhatsAppMessage: async (_instance: string, _jid: string, _id: string, _text: string) => ({ ok: true }),
  blockWhatsAppContact: async (_instance: string, _jid: string, _block: boolean) => ({ ok: true }),
  markWhatsAppAsRead: async (_jid: string, _instance: string, _msgId?: string): Promise<void> => {},
  reactWhatsAppMessage: async (_instance: string, _jid: string, _id: string, _emoji: string) => ({ ok: true }),
  deleteWhatsAppMessage: async (_instance: string, _jid: string, _id: string) => ({ ok: true }),
  forwardWhatsAppMessage: async (_instance: string, _to: string, _payload: any) => ({ ok: true }),
  sendWhatsAppPresence: async (_to: string, _presence: string, _instance: string) => ({ ok: true }),
  syncWhatsAppEvents: async (_after?: number) => ({ ok: true, events: [], timestamp: Date.now() }),
  syncWhatsAppAvatar: async (_jid: string, _instance: string) => ({ ok: true }),
  getWhatsAppLabels: async (_instance: string) => ({ labels: [] }),
  pinWhatsAppChat: async (_id: number, _pin: boolean) => ({ ok: true }),
  archiveWhatsAppChat: async (_id: number, _archived: boolean) => ({ ok: true }),
  deleteWhatsAppChat: async (_id: number) => ({ ok: true }),
  uploadFile: async (_file: File) => ({ url: '' }),
  getInstanceErrors: async (_instance: string, _limit: number) => ({ errors: [] }),
  getInstanceConfigs: async (_instance: string) => ({}),
  getInstanceMetrics: async (_instance: string) => ({}),
  updateInstanceConfigs: async (_instance: string, _data: any) => ({ ok: true }),

  // ── AI Bots ──
  getAICredentials: (instanceId: string) => chatbotApi.getCredentials(instanceId),
  createAICredential: (instanceId: string, name: string, apiKey: string, provider: 'GEMINI' | 'OPENAI' = 'GEMINI') =>
    chatbotApi.createCredential(instanceId, { name, apiKey, provider }),
  deleteAICredential: (instanceId: string, credId: string) =>
    chatbotApi.deleteCredential(instanceId, credId),
  getAIBots: (instanceId: string) => chatbotApi.getBots(instanceId),
  createAIBot: (instanceId: string, data: Record<string, unknown>) =>
    chatbotApi.createBot(instanceId, data),
  updateAIBot: (instanceId: string, botId: string, data: Record<string, unknown>) =>
    chatbotApi.updateBot(instanceId, botId, data),
  deleteAIBot: (instanceId: string, botId: string) =>
    chatbotApi.deleteBot(instanceId, botId),

  // ── Generic fallbacks ──
  post: async (url: string, data?: any) => { const r = await http.post(url, data); return r.data },
  get:  async (url: string, cfg?: any)  => { const r = await http.get(url, cfg);   return r.data },
  put:  async (url: string, data?: any) => { const r = await http.put(url, data);  return r.data },
  delete: async (url: string, cfg?: any) => { const r = await http.delete(url, cfg); return r.data },
}
