import axios from 'axios';

const api = axios.create({
  baseURL: '/api',
  withCredentials: true,
});

api.interceptors.response.use(
  res => res,
  err => {
    if (err.response?.status === 401) {
      window.dispatchEvent(new CustomEvent('auth:logout'));
    }
    return Promise.reject(err);
  }
);

export const AnalyticsService = {
  getDashboard: () => api.get('/analytics/dashboard').then(r => r.data),
};

export const RaffleService = {
  list: () => api.get('/raffle').then(r => r.data),
  getDetail: (id: number) => api.get(`/raffle/${id}`).then(r => r.data),
  draw: (id: number) => api.post(`/raffle/${id}/draw`).then(r => r.data),
  create: (data: any) => api.post('/raffle', data).then(r => r.data),
  update: (id: number, data: any) => api.put(`/raffle/${id}`, data).then(r => r.data),
  delete: (id: number) => api.delete(`/raffle/${id}`).then(r => r.data),
  getDiscounts: (id: number) => api.get(`/raffle/${id}/discounts`).then(r => r.data),
  saveDiscounts: (id: number, tiers: Array<{ min_qty: number; discount_pct: number }>) =>
    api.post(`/raffle/${id}/discounts`, { tiers }).then(r => r.data),
  getFlashPromo: (id: number) => api.get(`/raffle/${id}/flash-promo`).then(r => r.data),
  createFlashPromo: (id: number, data: { discount_pct: number; duration_minutes: number; label?: string }) =>
    api.post(`/raffle/${id}/flash-promo`, data).then(r => r.data),
  cancelFlashPromo: (raffleId: number, promoId: number) =>
    api.delete(`/raffle/${raffleId}/flash-promo/${promoId}`).then(r => r.data),
};

export const PromotionService = {
  list: () => api.get('/promotions/all').then(r => r.data),
  create: (data: any) => api.post('/promotions', data).then(r => r.data),
  update: (id: number, data: any) => api.put(`/promotions/${id}`, data).then(r => r.data),
  delete: (id: number) => api.delete(`/promotions/${id}`).then(r => r.data),
};

export const UserService = {
  list: () => api.get('/users').then(r => r.data),
  update: (id: number, data: any) => api.put(`/users/${id}`, data).then(r => r.data),
  delete: (id: number) => api.delete(`/users/${id}`).then(r => r.data),
};

export const TenantService = {
  getConfig: () => api.get('/tenant/config').then(r => r.data),
  updateConfig: (data: {
    primary_color?: string; secondary_color?: string;
    logo_url?: string; favicon_url?: string;
    contact_email?: string; contact_phone?: string; app_url?: string;
  }) => api.put('/tenant/config', data).then(r => r.data),
};

export const SettingsService = {
  getAsaasKey: () => api.get('/settings/asaas').then(r => r.data),
  saveAsaasKey: (key: string) => api.post('/settings/asaas', { key }).then(r => r.data),
};

export const PluginService = {
  list: () => api.get('/plugins').then(r => r.data),
  activate: (id: string) => api.post(`/plugins/${id}/activate`).then(r => r.data),
  deactivate: (id: string) => api.post(`/plugins/${id}/deactivate`).then(r => r.data),
  getConfig: (id: string) => api.get(`/plugins/${id}/config`).then(r => r.data),
  setConfig: (id: string, data: any) => api.put(`/plugins/${id}/config`, data).then(r => r.data),
};

export const OrderService = {
  list: (params?: { status?: string; from?: string; to?: string }) =>
    api.get('/orders', { params }).then(r => r.data) as Promise<any[]>,
};

export const ClaimService = {
  list: (status?: string) =>
    api.get('/claims', { params: status ? { status } : {} }).then(r => r.data) as Promise<any[]>,
  updateStatus: (id: number, status: string) =>
    api.patch(`/claims/${id}`, { status }).then(r => r.data),
};

export const ClubReportService = {
  get: () => api.get('/admin/club/reports').then(r => r.data) as Promise<any>,
  exportCsv: (params?: { club_id?: number; status?: string }) =>
    api.get('/admin/club/members', { params: { ...params, limit: 9999 } }).then(r => r.data) as Promise<any[]>,
};

export const ClubService = {
  // Membros
  listMembers: (clubId: number, params?: { status?: string; limit?: number; offset?: number }) =>
    api.get('/admin/club/members', { params: { club_id: clubId, ...params } }).then(r => r.data) as Promise<any[]>,
  updateMemberStatus: (id: number, status: string) =>
    api.patch(`/admin/club/members/${id}`, { status }).then(r => r.data),
  // Parceiros
  listPartners: (clubId: number) =>
    api.get('/admin/club/partners', { params: { club_id: clubId } }).then(r => r.data) as Promise<any[]>,
  createPartner: (data: any) =>
    api.post('/admin/club/partners', data).then(r => r.data),
  updatePartner: (id: number, data: any) =>
    api.put(`/admin/club/partners/${id}`, data).then(r => r.data),
  deletePartner: (id: number) =>
    api.delete(`/admin/club/partners/${id}`).then(r => r.data),
  // Planos
  listPlans: (clubId: number) =>
    api.get('/admin/club/plans', { params: { club_id: clubId } }).then(r => r.data) as Promise<any[]>,
  createPlan: (data: any) =>
    api.post('/admin/club/plans', data).then(r => r.data),
  updatePlan: (id: number, data: any) =>
    api.put(`/admin/club/plans/${id}`, data).then(r => r.data),
  deletePlan: (id: number) =>
    api.delete(`/admin/club/plans/${id}`).then(r => r.data),
  // Conteúdo (condições + regras)
  saveContent: (clubId: number, data: { conditions: string; rules: string }) =>
    api.put(`/admin/club/${clubId}/content`, data).then(r => r.data),
  // FAQs
  listFaqs: (clubId: number) =>
    api.get('/admin/club/faqs', { params: { club_id: clubId } }).then(r => r.data) as Promise<any[]>,
  createFaq: (data: any) =>
    api.post('/admin/club/faqs', data).then(r => r.data),
  updateFaq: (id: number, data: any) =>
    api.put(`/admin/club/faqs/${id}`, data).then(r => r.data),
  deleteFaq: (id: number) =>
    api.delete(`/admin/club/faqs/${id}`).then(r => r.data),
};

export const JobsService = {
  // KPIs
  kpi: () => api.get('/admin/jobs/kpi').then(r => r.data) as Promise<{ active: number; inactive: number; total_applications: number; hired: number }>,
  // Vagas
  list: (params?: Record<string, any>) =>
    api.get('/admin/jobs', { params }).then(r => r.data) as Promise<{ jobs: any[]; total: number }>,
  create: (data: any) => api.post('/admin/jobs', data).then(r => r.data),
  update: (id: number, data: any) => api.put(`/admin/jobs/${id}`, data).then(r => r.data),
  toggle: (id: number) => api.patch(`/admin/jobs/${id}/toggle`).then(r => r.data),
  remove: (id: number) => api.delete(`/admin/jobs/${id}`).then(r => r.data),
  // Candidaturas
  getApplications: (jobId: number, params?: Record<string, any>) =>
    api.get(`/admin/jobs/${jobId}/applications`, { params }).then(r => r.data) as Promise<any[]>,
  getApplication: (id: number) => api.get(`/admin/applications/${id}`).then(r => r.data),
  updateApplication: (id: number, data: { status?: string; admin_notes?: string }) =>
    api.patch(`/admin/applications/${id}`, data).then(r => r.data),
  // Currículos
  searchResumes: (params?: Record<string, any>) =>
    api.get('/admin/resumes', { params }).then(r => r.data) as Promise<any[]>,
  getResume: (cpf: string) => api.get(`/admin/resumes/${cpf}`).then(r => r.data),
};

export const AdminMeService = {
  // Retorna admin + tenant + linkedAccount.
  // linkedAccount é o perfil de colaborador (accounts) vinculado ao admin.
  // Quando presente, o frontend usa linkedAccount.id como accountId na
  // Inbox Interna — eliminando a necessidade de um segundo login de equipe.
  get: () => api.get('/admin/me').then(r => r.data) as Promise<{
    admin: { id: number; username: string; nome: string | null; email: string | null; tenant_id: number; account_id: number | null }
    tenant: { id: number; slug: string; name: string; primary_color: string; secondary_color: string; logo_url: string | null }
    linkedAccount: { id: number; name: string; email: string; role: string; avatar_url: string | null } | null
  }>,

  // Vincula (ou desvincula) o admin a um account de colaborador.
  // account_id=null desvincula.
  linkAccount: (account_id: number | null) =>
    api.patch('/admin/me/account', { account_id }).then(r => r.data),
};

export const AdminService = {
  list: () => api.get('/admins').then(r => r.data),
  create: (data: any) => api.post('/admins', data).then(r => r.data),
  update: (id: number, data: any) => api.put(`/admins/${id}`, data).then(r => r.data),
  delete: (id: number) => api.delete(`/admins/${id}`).then(r => r.data),
};

export const PairService = {
  request: async (email: string, nwUrl: string) => {
    const res = await fetch('/api/pair/proxy/request', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ email, nwUrl }),
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || 'Erro ao solicitar código');
    return data;
  },
  confirm: async (email: string, code: string, nwUrl: string) => {
    const res = await fetch('/api/pair/proxy/confirm', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ email, code, nwUrl }),
    });
    const data = await res.json();
    if (!res.ok) throw new Error(data.error || 'Código inválido');
    return data;
  },
};

// ── NwService — proxy para /api/nw/v1/* (motor NewWhats) ─────────────────────
export const NwService = {
  getSessions: () => api.get('/nw/v1/sessions').then(r => r.data) as Promise<NwSession[]>,
  getQr:       (sessionId: string) => api.get(`/nw/v1/sessions/${sessionId}/qr`).then(r => r.data) as Promise<{ instanceId: string; qrBase64: string }>,
  getInbox:    (sessionId: string, search?: string, limit = 50) =>
    api.get('/nw/v1/inbox', { params: { session: sessionId, search, limit } }).then(r => r.data) as Promise<NwChat[]>,
  getMessages: (chatId: string, limit = 50, before?: string) =>
    api.get(`/nw/v1/inbox/${chatId}/messages`, { params: { limit, before } }).then(r => r.data) as Promise<NwMessage[]>,
  send:        (chatId: string, text: string) =>
    api.post(`/nw/v1/inbox/${chatId}/send`, { text }).then(r => r.data),
  markRead:    (chatId: string) =>
    api.post(`/nw/v1/inbox/${chatId}/read`).then(r => r.data),
  archive:     (chatId: string, archived: boolean) =>
    api.patch(`/nw/v1/inbox/${chatId}/archive`, { archived }).then(r => r.data),
  pin:         (chatId: string, pinned: boolean) =>
    api.patch(`/nw/v1/inbox/${chatId}/pin`, { pinned }).then(r => r.data),
  deleteChat:  (chatId: string) =>
    api.delete(`/nw/v1/inbox/${chatId}`).then(r => r.data),
  getWebhooks: () =>
    api.get('/nw/v1/webhooks').then(r => r.data) as Promise<NwWebhook[]>,
  createWebhook: (data: { url: string; events: string[]; secret: string }) =>
    api.post('/nw/v1/webhooks', data).then(r => r.data) as Promise<NwWebhook>,
  deleteWebhook: (id: string) =>
    api.delete(`/nw/v1/webhooks/${id}`).then(r => r.data),
  toggleWebhook: (id: string, active: boolean) =>
    api.patch(`/nw/v1/webhooks/${id}`, { active }).then(r => r.data) as Promise<NwWebhook>,
  secretariaAsk: (chatId: string, message: string, contactName?: string) =>
    api.post('/nw/v1/secretaria/ask', { chatId, message, contactName }).then(r => r.data) as Promise<NwSecretariaReply>,

  // Nova conversa — envia primeira mensagem para número sem chat existente
  startConversation: (sessionId: string, phone: string, text: string) =>
    api.post('/nw/v1/conversations', { sessionId, phone, text }).then(r => r.data) as Promise<{ ok: boolean; jid: string }>,

  // Gerenciamento de sessões (criar / remover no motor)
  createSession: (label: string) =>
    api.post('/nw/v1/sessions', { name: label }).then(r => r.data) as Promise<{ id: string; name: string; status: string }>,
  deleteSession: (sessionId: string) =>
    api.delete(`/nw/v1/sessions/${sessionId}`).then(r => r.data),

  // sec_numbers — metadados de cada número (categoria, prioridade, apelido)
  getNumbers: () =>
    api.get('/nw/v1/secretaria/numbers').then(r => r.data) as Promise<NwNumber[]>,
  saveNumber: (data: { instance_id: string; label: string; role: string; area?: string | null; priority: number; active?: boolean; notes?: string | null }) =>
    api.post('/nw/v1/secretaria/numbers', data).then(r => r.data) as Promise<NwNumber>,
  updateNumber: (id: string, data: Partial<NwNumber>) =>
    api.put(`/nw/v1/secretaria/numbers/${id}`, data).then(r => r.data) as Promise<NwNumber>,
  deleteNumber: (id: string) =>
    api.delete(`/nw/v1/secretaria/numbers/${id}`).then(r => r.data),

  // Métricas + modo auto-resposta (Frentes 2 e 5)
  getMetrics: (period?: '1d' | '7d' | '30d') =>
    api.get('/admin/nw/metrics', { params: { period: period ?? '7d' } }).then(r => r.data),
  getAutoReplyMode: () =>
    api.get('/admin/nw/auto-reply-mode').then(r => r.data) as Promise<{ mode: 'off' | 'automatico' }>,
  setAutoReplyMode: (mode: 'off' | 'automatico') =>
    api.put('/admin/nw/auto-reply-mode', { mode }).then(r => r.data),
  syncKnowledge: () =>
    api.post('/admin/nw/sync-knowledge').then(r => r.data),

  // Secretária — Agente
  secGetAgent: () =>
    api.get('/nw/v1/sec/agent').then(r => r.data),
  secCreateAgent: (data: any) =>
    api.post('/nw/v1/sec/agent', data).then(r => r.data),
  secUpdateAgent: (id: string, data: any) =>
    api.put(`/nw/v1/sec/agent/${id}`, data).then(r => r.data),

  // Secretária — Brain nodes
  secGetNodes: () =>
    api.get('/nw/v1/sec/nodes').then(r => r.data) as Promise<any[]>,
  secCreateNode: (data: { type: string; title: string; content: string }) =>
    api.post('/nw/v1/sec/nodes', data).then(r => r.data),
  secUpdateNode: (id: string, data: { type: string; title: string; content: string }) =>
    api.put(`/nw/v1/sec/nodes/${id}`, data).then(r => r.data),
  secDeleteNode: (id: string) =>
    api.delete(`/nw/v1/sec/nodes/${id}`).then(r => r.data),

  // Secretária — Agenda (slots)
  secGetSlots: () =>
    api.get('/nw/v1/sec/slots').then(r => r.data) as Promise<any[]>,
  secCreateSlot: (data: any) =>
    api.post('/nw/v1/sec/slots', data).then(r => r.data),
  secDeleteSlot: (id: string) =>
    api.delete(`/nw/v1/sec/slots/${id}`).then(r => r.data),

  // Secretária — Conversas
  secGetConversations: () =>
    api.get('/nw/v1/sec/conversations').then(r => r.data) as Promise<any[]>,
  secGetConvMessages: (id: string) =>
    api.get(`/nw/v1/sec/conversations/${id}/messages`).then(r => r.data) as Promise<any[]>,
  secFinalizeConv: (id: string) =>
    api.post(`/nw/v1/sec/conversations/${id}/finalize`).then(r => r.data),
  // Chat de teste inline (usa chatId fictício por sessão)
  secTestAsk: (testSessionId: string, message: string) =>
    api.post('/nw/v1/secretaria/ask', { chatId: `test-panel-${testSessionId}`, message, contactName: 'Teste Admin' }).then(r => r.data) as Promise<{ reply?: string; skipped?: boolean }>,

  // Secretária — API keys
  secGetKeys: () =>
    api.get('/nw/v1/sec/keys').then(r => r.data),
  secSaveKeys: (data: { openai_key?: string; gemini_key?: string; anthropic_key?: string; ollama_url?: string; admin_notify_phone?: string }) =>
    api.put('/nw/v1/sec/keys', data).then(r => r.data),

  // Secretária — Handoff humano ↔ IA (estado local, independente do motor)
  getHandoffMode: (chatId: string) =>
    api.get(`/nw/handoff/${encodeURIComponent(chatId)}`).then(r => r.data) as Promise<{ mode: 'ia' | 'humano'; handoffHumanAt: string | null }>,
  setHandoffMode: (chatId: string, mode: 'ia' | 'humano') =>
    api.patch(`/nw/handoff/${encodeURIComponent(chatId)}`, { mode }).then(r => r.data) as Promise<{ mode: 'ia' | 'humano'; handoffHumanAt: string | null }>,

  // ── Mensagens ricas ──────────────────────────────────────────────────────
  sendRich: (chatId: string, payload: Record<string, unknown>) =>
    api.post(`/nw/v1/inbox/${chatId}/send`, payload).then(r => r.data),

  // ── Templates de mensagem ────────────────────────────────────────────────
  listTemplates: (params?: { type?: string; search?: string }) =>
    api.get('/nw/v1/templates', { params }).then(r => r.data) as Promise<NwTemplate[]>,
  createTemplate: (data: { name: string; type: string; payload: Record<string, unknown>; tags?: string[]; description?: string }) =>
    api.post('/nw/v1/templates', data).then(r => r.data) as Promise<NwTemplate>,
  deleteTemplate: (id: string) =>
    api.delete(`/nw/v1/templates/${id}`).then(r => r.data),
  markTemplateUsed: (id: string) =>
    api.post(`/nw/v1/templates/${id}/use`).then(r => r.data),

  // ── Agendamentos ─────────────────────────────────────────────────────────
  listScheduled: () =>
    api.get('/nw/v1/scheduled').then(r => r.data) as Promise<any[]>,
  createScheduled: (data: Record<string, unknown>) =>
    api.post('/nw/v1/scheduled', data).then(r => r.data),
  deleteScheduled: (id: string) =>
    api.delete(`/nw/v1/scheduled/${id}`).then(r => r.data),
  pauseScheduled: (id: string) =>
    api.post(`/nw/v1/scheduled/${id}/pause`).then(r => r.data),
  resumeScheduled: (id: string) =>
    api.post(`/nw/v1/scheduled/${id}/resume`).then(r => r.data),
};

export const EscalationService = {
  assume: (data: { chatId: string; protocolNumber?: string; chatName?: string }) =>
    api.post('/admin/escalation/assume', data).then(r => r.data) as Promise<{ threadId: string; msgId: number; protocolNumber?: string }>,
  transfer: (data: { threadId?: string; toAccountId: number; protocolNumber?: string; message?: string }) =>
    api.post('/admin/protocol/transfer', data).then(r => r.data) as Promise<{ threadId: string; msgId: number }>,
};

export const HumanApiService = {
  answer: (requestId: number, answer: string) =>
    api.post(`/human-api/answer/${requestId}`, { answer }).then(r => r.data) as Promise<{ ok: boolean; requestId: number; threadId: string }>,
};

export const ProtocolService = {
  close:  (data: { threadId: string; chatId: string; protocolNumber?: string }) =>
    api.post('/admin/protocol/close', data).then(r => r.data),
  flag:   (data: { threadId: string; type: 'complaint' | 'suggestion' | 'compliment'; note?: string }) =>
    api.post('/admin/protocol/flag', data).then(r => r.data),
};

export const KnowledgeService = {
  save:    (data: { question: string; answer: string; sectorId?: number }) =>
    api.post('/admin/knowledge/save', data).then(r => r.data),
  promote: (id: number) =>
    api.post(`/admin/knowledge/promote/${id}`).then(r => r.data),
  list:    (promotedOnly = false) =>
    api.get(`/admin/knowledge${promotedOnly ? '' : '?promoted=false'}`).then(r => r.data),
};

// Fase 13: Direct Messages (DMs entre colaboradores)
export const DirectMessageService = {
  send: (toAccountId: number, content: string) =>
    api.post('/admin/inbox/direct-message', { to_account: toAccountId, content }).then(r => r.data),

  getConversation: (otherAccountId: number, limit = 50) =>
    api.get(`/admin/inbox/direct/${otherAccountId}?limit=${limit}`).then(r => r.data),

  getLastMessages: () =>
    api.get('/admin/inbox/direct-messages').then(r => r.data),

  getColleagues: () =>
    api.get('/admin/inbox/colleagues').then(r => r.data),

  markAsRead: (messageId: number) =>
    api.patch(`/admin/inbox/direct/${messageId}/read`).then(r => r.data),
};

export interface GroupChat {
  id:              number
  sector_id:       number
  name:            string
  icon:            string
  color:           string
  last_message:    string | null
  last_message_at: string | null
  unread_count:    number
}

export interface GroupMessage {
  id:            number
  from_account:  number
  content:       string
  created_at:    string
  sender_name:   string | null
  sender_avatar: string | null
}

export const GroupChatService = {
  list: (): Promise<GroupChat[]> =>
    api.get('/admin/inbox/groups').then(r => r.data),

  getMessages: (groupId: number, limit = 50, before?: string): Promise<GroupMessage[]> => {
    const params = new URLSearchParams({ limit: String(limit) })
    if (before) params.set('before', before)
    return api.get(`/admin/inbox/groups/${groupId}/messages?${params}`).then(r => r.data)
  },

  sendMessage: (groupId: number, content: string): Promise<GroupMessage> =>
    api.post(`/admin/inbox/groups/${groupId}/message`, { content }).then(r => r.data),

  getMembers: (groupId: number) =>
    api.get(`/admin/inbox/groups/${groupId}/members`).then(r => r.data),

  markRead: (groupId: number) =>
    api.post(`/admin/inbox/groups/${groupId}/read`).then(r => r.data),
};

export interface BroadcastItem {
  id:            number
  from_account:  number | null
  content:       string
  created_at:    string
  sender_name:   string | null
  sender_avatar: string | null
}

export const BroadcastService = {
  send: (content: string): Promise<BroadcastItem> =>
    api.post('/admin/inbox/broadcast', { content }).then(r => r.data),

  list: (): Promise<{ items: BroadcastItem[]; unread_count: number }> =>
    api.get('/admin/inbox/broadcasts').then(r => r.data),

  markSeen: () =>
    api.post('/admin/inbox/broadcasts/seen').then(r => r.data),
};

export interface NwSession {
  id:        string;
  name:      string;
  phone:     string | null;
  status:    'CONNECTED' | 'DISCONNECTED' | 'QR_PENDING' | 'CONNECTING' | 'BANNED';
  avatar:    string | null;
  createdAt: string;
}

export interface NwChat {
  id:            string;
  jid:           string;
  displayName:   string | null;
  avatar:        string | null;
  phone:         string;
  unreadCount:   number;
  lastMessageAt: string | null;
  isPinned:      boolean;
  isArchived:    boolean;
  lastMessage: {
    body:      string | null;
    type:      string;
    fromMe:    boolean;
    status:    string;
    timestamp: string;
  } | null;
}

export interface NwMessage {
  id:        string;
  messageId: string;
  fromMe:    boolean;
  type:      string;
  body:      string | null;
  caption:   string | null;
  mediaUrl:  string | null;
  mimeType:  string | null;
  fileName:  string | null;
  status:    string;
  timestamp: string;
  pushName:  string | null;
  senderJid: string | null;
}

export interface NwWebhook {
  id:        string;
  url:       string;
  events:    string[];
  active:    boolean;
  createdAt: string;
}

export interface NwSecretariaReply {
  reply:          string;
  conversationId: string;
  protocolNumber: string;
}

export interface NwNumber {
  id:          string;
  instance_id: string;   // corresponde ao NwSession.id no motor
  label:       string;
  role:        string;   // notificacoes | entregas | suporte | marketing | geral
  area:        string | null;
  priority:    number;   // 1=Principal, 2=Fallback, 3=Terciário…
  active:      boolean;
  notes:       string | null;
  created_at:  string;
  updated_at:  string;
}

export interface NwTemplate {
  id:          string;
  name:        string;
  description: string | null;
  type:        'TEXT' | 'BUTTONS' | 'INTERACTIVE' | 'LIST' | 'POLL' | 'CAROUSEL';
  payload:     Record<string, unknown>;
  tags:        string[];
  usageCount:  number;
  createdAt:   string;
  updatedAt:   string;
}

export type NwTemplateType = NwTemplate['type'];

// ── Equipe Virtual (Fase 12) ─────────────────────────────────────────────────

export const AccountsService = {
  list:   (params?: { role?: string; active?: string }) =>
    api.get('/admin/accounts', { params }).then(r => r.data) as Promise<any[]>,
  get:    (id: number) =>
    api.get(`/admin/accounts/${id}`).then(r => r.data),
  create: (data: { name: string; email?: string; password?: string; role?: string; phone?: string; avatar_url?: string }) =>
    api.post('/admin/accounts', data).then(r => r.data),
  update: (id: number, data: Partial<{ name: string; email: string; password: string; role: string; phone: string; availability: string; avatar_url: string; active: boolean; phone_connected: boolean }>) =>
    api.put(`/admin/accounts/${id}`, data).then(r => r.data),
  remove: (id: number) =>
    api.delete(`/admin/accounts/${id}`).then(r => r.data),
};

export const SectorsService = {
  list:   () =>
    api.get('/admin/sectors').then(r => r.data) as Promise<any[]>,
  get:    (id: number) =>
    api.get(`/admin/sectors/${id}`).then(r => r.data),
  create: (data: { name: string; description?: string; icon?: string; color?: string; sla_minutes?: number }) =>
    api.post('/admin/sectors', data).then(r => r.data),
  update: (id: number, data: any) =>
    api.put(`/admin/sectors/${id}`, data).then(r => r.data),
  remove: (id: number) =>
    api.delete(`/admin/sectors/${id}`).then(r => r.data),
  // Cérebro por setor
  getBrain:    (sectorId: number) =>
    api.get(`/admin/sectors/${sectorId}/brain`).then(r => r.data) as Promise<any[]>,
  createBrain: (sectorId: number, data: { type: string; content: string; sort_order?: number }) =>
    api.post(`/admin/sectors/${sectorId}/brain`, data).then(r => r.data),
  updateBrain: (id: number, data: any) =>
    api.put(`/admin/sectors/brain/${id}`, data).then(r => r.data),
  deleteBrain: (id: number) =>
    api.delete(`/admin/sectors/brain/${id}`).then(r => r.data),
};

export const TeamMembersService = {
  list:   (params?: { sector_id?: number }) =>
    api.get('/admin/team-members', { params }).then(r => r.data) as Promise<any[]>,
  add:    (data: { account_id: number; sector_id: number; function?: string; is_primary?: boolean; notify_escalation?: boolean; notify_human_api?: boolean }) =>
    api.post('/admin/team-members', data).then(r => r.data),
  update: (id: number, data: Partial<{ function: string; is_primary: boolean; on_duty: boolean; notify_escalation: boolean; notify_human_api: boolean }>) =>
    api.put(`/admin/team-members/${id}`, data).then(r => r.data),
  remove: (id: number) =>
    api.delete(`/admin/team-members/${id}`).then(r => r.data),
};

export const InboxInternaService = {
  listThreads:  (accountId: number) =>
    api.get('/admin/inbox/threads', { params: { account_id: accountId } }).then(r => r.data) as Promise<any[]>,
  getThread:    (threadId: string) =>
    api.get(`/admin/inbox/threads/${threadId}`).then(r => r.data) as Promise<any[]>,
  postMessage:  (data: { thread_id?: string; from_account?: number; to_account?: number; sector_id?: number; type?: string; content: string; ref_id?: string }) =>
    api.post('/admin/inbox/messages', data).then(r => r.data),
  markRead:     (threadId: string, accountId: number) =>
    api.post(`/admin/inbox/threads/${threadId}/read`, { account_id: accountId }).then(r => r.data),
  unreadCount:  (accountId: number) =>
    api.get('/admin/inbox/unread', { params: { account_id: accountId } }).then(r => r.data) as Promise<{ count: number }>,
};

// ── Módulo Cotação Online ─────────────────────────────────────────────────────

export const ClienteService = {
  list:   (params?: any) => api.get('/clientes', { params }).then(r => r.data),
  get:    (id: number)   => api.get(`/clientes/${id}`).then(r => r.data),
  create: (data: any)    => api.post('/clientes', data).then(r => r.data),
  update: (id: number, data: any) => api.put(`/clientes/${id}`, data).then(r => r.data),
  delete: (id: number)   => api.delete(`/clientes/${id}`).then(r => r.data),
  // Endereços
  listEnderecos:    (id: number)          => api.get(`/clientes/${id}/enderecos`).then(r => r.data),
  addEndereco:      (id: number, d: any)  => api.post(`/clientes/${id}/enderecos`, d).then(r => r.data),
  updateEndereco:   (id: number, eid: number, d: any) => api.put(`/clientes/${id}/enderecos/${eid}`, d).then(r => r.data),
  deleteEndereco:   (id: number, eid: number) => api.delete(`/clientes/${id}/enderecos/${eid}`).then(r => r.data),
  // Telefones
  listTelefones:    (id: number)          => api.get(`/clientes/${id}/telefones`).then(r => r.data),
  addTelefone:      (id: number, d: any)  => api.post(`/clientes/${id}/telefones`, d).then(r => r.data),
  updateTelefone:   (id: number, tid: number, d: any) => api.put(`/clientes/${id}/telefones/${tid}`, d).then(r => r.data),
  deleteTelefone:   (id: number, tid: number) => api.delete(`/clientes/${id}/telefones/${tid}`).then(r => r.data),
  // Responsáveis
  listResponsaveis: (id: number)          => api.get(`/clientes/${id}/responsaveis`).then(r => r.data),
  addResponsavel:   (id: number, d: any)  => api.post(`/clientes/${id}/responsaveis`, d).then(r => r.data),
  updateResponsavel:(id: number, rid: number, d: any) => api.put(`/clientes/${id}/responsaveis/${rid}`, d).then(r => r.data),
  deleteResponsavel:(id: number, rid: number) => api.delete(`/clientes/${id}/responsaveis/${rid}`).then(r => r.data),
};

export interface Produto {
  id: number
  tenant_id: number
  sku: string | null
  nome: string
  descricao: string | null
  unidade: string
  preco: number
  preco_promocional: number | null
  estoque: number
  categoria: string | null
  imagem: string | null
  ativo: boolean
  created_at: string
  updated_at: string
}

export const ProdutoService = {
  list:         (params?: any) => api.get('/produtos/admin/all', { params }).then(r => r.data as Produto[]),
  listPublic:   (params?: any) => api.get('/produtos', { params }).then(r => r.data as Produto[]),
  categorias:   ()             => api.get('/produtos/categorias').then(r => r.data as string[]),
  get:          (id: number)   => api.get(`/produtos/${id}`).then(r => r.data as Produto),
  create:       (data: any)    => api.post('/produtos', data).then(r => r.data as Produto),
  update:       (id: number, data: any) => api.put(`/produtos/${id}`, data).then(r => r.data),
  updateEstoque:(id: number, estoque: number) => api.patch(`/produtos/${id}/estoque`, { estoque }).then(r => r.data),
  updatePreco:  (id: number, preco: number)   => api.patch(`/produtos/${id}/preco`, { preco }).then(r => r.data),
  updatePromo:  (id: number, preco_promocional: number | null) => api.patch(`/produtos/${id}/preco`, { preco_promocional }).then(r => r.data),
  delete:       (id: number)   => api.delete(`/produtos/${id}`).then(r => r.data),
  importar:     (produtos: any[]) => api.post('/produtos/importar', { produtos }).then(r => r.data),
};

export const CotacaoService = {
  listPedidos:      (params?: any) => api.get('/cotacoes/admin/pedidos', { params }).then(r => r.data),
  getPedido:        (id: number)   => api.get(`/cotacoes/admin/pedidos/${id}`).then(r => r.data),
  contadores:       ()             => api.get('/cotacoes/admin/pedidos/contadores').then(r => r.data),
  listFinanceiro:   ()             => api.get('/cotacoes/admin/financeiro').then(r => r.data) as Promise<any[]>,
  financeiroDecisao:(id: number, acao: 'aprovar'|'rejeitar', obs?: string) => api.patch(`/cotacoes/admin/financeiro/${id}`, { acao, obs }).then(r => r.data),
  wppSemResposta:  (limiar = 5)  => api.get(`/cotacoes/admin/whatsapp/sem-resposta?limiar=${limiar}`).then(r => r.data) as Promise<any[]>,
  notificacoes:     (minutes?: number) => api.get('/cotacoes/admin/pedidos/notificacoes', { params: { minutes } }).then(r => r.data) as Promise<any[]>,
  updateStatus:     (id: number, status: string) => api.patch(`/cotacoes/admin/pedidos/${id}/status`, { status }).then(r => r.data),
  atribuirEquipe:   (id: number, equipe_id: number) => api.patch(`/cotacoes/admin/pedidos/${id}/equipe`, { equipe_id }).then(r => r.data),
  marcarSeparado:   (itemId: number, separado: boolean) => api.patch(`/cotacoes/admin/pedidos/itens/${itemId}/separado`, { separado }).then(r => r.data),
  marcarEntregue:   (id: number, responsavel?: string) => api.patch(`/cotacoes/admin/pedidos/${id}/status`, { status: 'entregue', responsavel_entrega: responsavel }).then(r => r.data),
  marcarEmbalado:   (id: number, embalador: string) => api.patch(`/cotacoes/admin/pedidos/${id}/embalagem`, { embalador }).then(r => r.data),
  marcarEmbaladoPorId: (id: number, embalador_id: number) =>
    api.patch(`/cotacoes/admin/pedidos/${id}/embalagem`, { embalador_id }).then(r => r.data),
  marcarEntreguePorId: (id: number, expedidor_id: number) =>
    api.patch(`/cotacoes/admin/pedidos/${id}/status`, { status: 'entregue', expedidor_id }).then(r => r.data),

  // Atribuição de separador/auditor/fiscal por id de colaborador
  setResponsavel: (id: number, funcao: 'separador'|'auditor'|'fiscal', account_id: number) =>
    api.patch(`/cotacoes/admin/pedidos/${id}/responsavel/${funcao}`, { account_id }).then(r => r.data),

  // Registro de cupom fiscal emitido externamente (PDV/ECF). Sem integração SEFAZ.
  registrarCupom: (id: number, payload: { numero?: string; chave?: string }) =>
    api.post(`/cotacoes/admin/pedidos/${id}/cupom`, payload).then(r => r.data) as Promise<{
      ok: boolean;
      cupom_numero: string | null;
      cupom_chave: string | null;
      cupom_emitido_em: string | null;
      cupom_emitido_por: number | null;
      cupom_emitido_por_nome: string | null;
    }>,

  // Lista de colaboradores aptos para uma função (filtra pelo setor do colaborador)
  listColaboradores: (funcao: 'separador'|'embalador'|'auditor'|'fiscal'|'expedidor') =>
    api.get('/cotacoes/admin/colaboradores/disponiveis', { params: { funcao } }).then(r => r.data) as Promise<{
      configurado: boolean;
      setores_aceitos?: string[];
      colaboradores: Array<{
        id: number; name: string; email: string | null; role: string;
        availability: 'online'|'busy'|'offline'; avatar_url: string | null;
        phone_connected: boolean; on_duty: boolean;
        sector_match?: string;
        pedidos_ativos: number; ultimo_pedido_em: string | null;
      }>;
    }>,
};

// ── Inbox Interno ─────────────────────────────────────────────────────────────

export const InboxInternoService = {
  contadores:          ()                   => api.get('/cotacoes/admin/inbox/contadores').then(r => r.data) as Promise<{ total: number; por_setor: Array<{ setor: string; total: string }> }>,
  listBySetor:         (setor: string, naoLidas?: boolean) =>
    api.get(`/cotacoes/admin/inbox/setor/${setor}`, { params: { nao_lidas: naoLidas } }).then(r => r.data) as Promise<any[]>,
  listByPedido:        (pedidoId: number)   => api.get(`/cotacoes/admin/inbox/pedido/${pedidoId}`).then(r => r.data) as Promise<any[]>,
  enviar:              (data: { pedido_id?: number; setor: string; mensagem: string }) =>
    api.post('/cotacoes/admin/inbox', data).then(r => r.data),
  marcarLida:          (id: number)         => api.patch(`/cotacoes/admin/inbox/${id}/lida`).then(r => r.data),
  marcarTodasPedido:   (pedidoId: number)   => api.patch(`/cotacoes/admin/inbox/pedido/${pedidoId}/lidas`).then(r => r.data),
  marcarTodasSetor:    (setor: string)      => api.patch(`/cotacoes/admin/inbox/setor/${setor}/lidas`).then(r => r.data),
};

// ── NW-Teams: proxy de sectors/teams do WA-Inbox ─────────────────────────────

export interface NwTeam { id: string; name: string; isActive: boolean }
export interface NwSector { id: string; name: string; isActive: boolean; teams: NwTeam[] }

export const NwTeamsService = {
  list: () => api.get('/admin/nw-teams').then(r => r.data) as Promise<NwSector[]>,
};

// Atualiza AccountsService para incluir campos de vínculo WA-Inbox
export const AccountsServiceV2 = {
  ...AccountsService,
  update: (id: number, data: Partial<{
    name: string; email: string; password: string; role: string; phone: string;
    availability: string; avatar_url: string; active: boolean; phone_connected: boolean;
    nw_team_id: string | null; nw_sector_id: string | null;
  }>) => api.put(`/admin/accounts/${id}`, data).then(r => r.data),
};

export default api;
