const API_BASE = import.meta.env.VITE_API_BASE || 'https://api.doormile.com/api/v1';

const getHeaders = () => {
  const token = localStorage.getItem('auth_token');
  return {
    'Content-Type': 'application/json',
    ...(token ? { 'Authorization': `Bearer ${token}` } : {})
  };
};

const parseJson = (res) => res.status === 204 ? {} : res.json().catch(() => ({}));

const extractArray = (json) => (Array.isArray(json) ? json : (Array.isArray(json?.data) ? json.data : []));

export async function fetchClients() {
  const res = await fetch(`${API_BASE}/crm/clients?limit=1000`, { headers: getHeaders() });
  if (!res.ok) throw new Error('Failed to fetch clients');
  const json = await res.json();
  return extractArray(json);
}

export async function loginAdmin(email, password) {
  const res = await fetch(`${API_BASE}/admin/login`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password }),
  });
  if (!res.ok) {
    const errorData = await res.json().catch(() => ({}));
    throw new Error(errorData.error || 'Failed to login');
  }
  return res.json();
}

export async function createClient(payload) {
  const res = await fetch(`${API_BASE}/crm/clients`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.error || err.message || 'Failed to create client');
  }
  return parseJson(res);
}

export async function updateClient(id, payload) {
  const res = await fetch(`${API_BASE}/crm/clients/${id}`, {
    method: 'PUT',
    headers: getHeaders(),
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.error || err.message || 'Failed to update client');
  }
  return parseJson(res);
}

export async function deleteClient(id) {
  const res = await fetch(`${API_BASE}/crm/clients/${id}`, {
    method: 'DELETE',
    headers: getHeaders()
  });
  if (!res.ok) throw new Error('Failed to delete client');
  return parseJson(res);
}

export async function fetchUsers() {
  const res = await fetch(`${API_BASE}/admin/users?limit=1000`, { headers: getHeaders() });
  if (!res.ok) throw new Error('Failed to fetch users');
  const json = await res.json();
  return extractArray(json);
}

export async function createUser(payload) {
  const res = await fetch(`${API_BASE}/admin/users`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.error || err.message || 'Failed to create user');
  }
  return parseJson(res);
}

export async function updateUser(id, payload) {
  const res = await fetch(`${API_BASE}/admin/users/${id}`, {
    method: 'PUT',
    headers: getHeaders(),
    body: JSON.stringify(payload),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error(err.error || err.message || 'Failed to update user');
  }
  return parseJson(res);
}

export async function deleteUser(id) {
  const res = await fetch(`${API_BASE}/admin/users/${id}`, {
    method: 'DELETE',
    headers: getHeaders()
  });
  if (!res.ok) throw new Error('Failed to delete user');
  return parseJson(res);
}

export async function fetchDashboard() {
  const res = await fetch(`${API_BASE}/admin/dashboard`, { headers: getHeaders() });
  if (!res.ok) throw new Error('Failed to fetch dashboard');
  return res.json();
}

export async function deleteCompetitorBranch(id) {
  const res = await fetch(`${API_BASE}/admin/competitor-branches/${id}`, {
    method: 'DELETE',
    headers: getHeaders()
  });
  if (!res.ok) throw new Error('Failed to delete survey record');
  return parseJson(res);
}
