import https from "@/services/https"

const getAuthHeaders = () => {
  if (typeof window === 'undefined') {
    // Return empty headers or throw an error if called during SSR/SSG
    // For now, returning basic content type.
    return { "Content-Type": "application/json" };
  }

  const token = localStorage.getItem("token");
  // if (authData) {
    // const parsedData = JSON.parse(authData);
    if (token) {
      return {
        "Content-Type": "application/json",
        "x-auth-token": token,
      };
    }
  // }
  return { "Content-Type": "application/json" };
};

const buildQueryParams = (params) => {
  const query = Object.keys(params)
    .filter(key => params[key] !== undefined && params[key] !== null)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&');
  return query ? `?${query}` : '';
};

export const getAgentCommissions = async (startDate, endDate) => {
  const queryParams = buildQueryParams({ startDate, endDate });
  const response = await fetch(`${https.baseUrl}/commissions${queryParams}`, {
    headers: getAuthHeaders(),
  })
  if (!response.ok) {
    throw new Error("Failed to fetch agent commissions")
  }
  return response.json()
}

export const getSuperAgentCommissions = async (startDate, endDate) => {
  const queryParams = buildQueryParams({ startDate, endDate });
  const response = await fetch(`${https.baseUrl}/commissions/super-agent${queryParams}`, {
    headers: getAuthHeaders(),
  })
  if (!response.ok) {
    throw new Error("Failed to fetch super agent commissions")
  }
  return response.json()
}

export const getWithdrawalRequests = async () => {
  const response = await fetch(`${https.baseUrl}/admin/withdrawal-requests`, {
    headers: getAuthHeaders(),
  })
  if (!response.ok) {
    throw new Error("Failed to fetch withdrawal requests")
  }
  return response.json()
}

export const approveSuperAgentWithdrawal = async (withdrawalId, payload) => {
  const response = await fetch(
    `${https.baseUrl}/admin/approve-super-agent-withdrawal/${withdrawalId}`,
    {
      method: "PUT",
      headers: getAuthHeaders(),
      body: JSON.stringify(payload),
    }
  )
  if (!response.ok) {
    throw new Error("Failed to approve super agent withdrawal")
  }
  return response.json()
}

export const approveAgentWithdrawal = async (withdrawalId, payload) => {
  const response = await fetch(
    `${https.baseUrl}/admin/approve-agent-withdrawal/${withdrawalId}`,
    {
      method: "PUT",
      headers: getAuthHeaders(),
      body: JSON.stringify(payload),
    }
  )
  if (!response.ok) {
    throw new Error("Failed to approve agent withdrawal")
  }
  return response.json()
}

export const getCreditAdditions = async (startDate, endDate) => {
  const queryParams = buildQueryParams({ startDate, endDate });
  const response = await fetch(`${https.baseUrl}/admin/credit-additions${queryParams}`, {
    headers: getAuthHeaders(),
  })
  if (!response.ok) {
    throw new Error("Failed to fetch credit additions")
  }
  return response.json()
}

export const disburseAllCommissionsToCredit = async () => {
  const response = await fetch(`${https.baseUrl}/admin/commissions/disburse-all-to-credit`, {
    method: "POST",
    headers: getAuthHeaders(),
  });
  if (!response.ok) {
    throw new Error("Failed to disburse all commissions to credit.");
  }
  return response.json();
};

export const getPendingCommissionsSummary = async () => {
  const response = await fetch(`${https.baseUrl}/admin/commissions/pending-summary`, {
    headers: getAuthHeaders(),
  });
  if (!response.ok) {
    throw new Error("Failed to fetch pending commissions summary.");
  }
  return response.json();
};



