import fetch from 'node-fetch';

const BASE    = 'https://vianexu.com/clients/ecobe/admin/api';
const TIMEOUT = 10000;
const BOT_TOKEN = () => process.env.BOT_API_TOKEN || '';

async function get(path) {
  const res = await fetch(`${BASE}${path}`, { signal: AbortSignal.timeout(TIMEOUT) });
  if (!res.ok) throw new Error(`viaweb ${path} → ${res.status}`);
  return res.json();
}

async function post(path, body) {
  const res = await fetch(`${BASE}${path}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${BOT_TOKEN()}` },
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(TIMEOUT),
  });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(data.error || `viaweb POST ${path} → ${res.status}`);
  return data;
}

export async function getMentees() {
  return get('/mentees'); // returns array of slugs
}

export async function getCareerStrategy(slug) {
  return get(`/mentee/${slug}/career-strategy`);
}

export async function getCv(slug) {
  return get(`/mentee/${slug}/cv`);
}

export async function getJobTracking(slug) {
  return get(`/mentee/${slug}/jobtracking`);
}

export async function createMentee(data) {
  return post('/mentee/create', data);
}

export async function updateMentee(slug, data) {
  const res = await fetch(`${BASE}/mentee/${slug}/career-strategy`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${BOT_TOKEN()}` },
    body: JSON.stringify(data),
    signal: AbortSignal.timeout(TIMEOUT),
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(json.error || `PUT /mentee/${slug}/career-strategy → ${res.status}`);
  return json;
}

export async function loadClients() {
  const slugs = await getMentees();
  const results = await Promise.allSettled(
    slugs.map(async (slug) => {
      const cs = await getCareerStrategy(slug);
      return { slug, name: cs.leadName, meta: cs, profile: cs };
    })
  );
  return results
    .filter(r => r.status === 'fulfilled')
    .map(r => r.value);
}
