import { csrfHeadersFor } from '../auth/auth-api-client.js';
/** File purpose (plain language): centralizes enterprise WeChat asset requests and turns API envelopes into usable data. */

/** Code purpose (plain language): sends an API request and exposes either its data or readable error. Related files: WecomAccountView.js, WecomAccountController.java. Data flow: view action -> request -> ApiResponse -> view state. */
async function request(path, options = {}) {
  const headers = await csrfHeadersFor(path, (options.method || 'GET').toUpperCase());
  const response = await fetch(path, { credentials: 'include', headers: { 'Content-Type': 'application/json', ...headers }, ...options });
  const payload = await response.json();
  if (!response.ok || payload.code !== 200) throw new Error(payload.message || '企业微信资产请求失败');
  return payload.data;
}

/** Code purpose (plain language): loads a filtered enterprise WeChat asset page. Related files: WecomAccountView.js, WecomAccountController.java. Data flow: filters -> URL params -> GET list -> table. */
export function listWecomAccounts(query) {
  const params = new URLSearchParams();
  Object.entries(query).forEach(([key, value]) => { if (value !== null && value !== undefined && value !== '' && value !== 'ALL') params.set(key, value); });
  return request(`/api/wecom-accounts?${params}`);
}

/** Code purpose (plain language): saves the create-dialog values. Related files: WecomAccountView.js, WecomAccountController.java. Data flow: dialog submit -> POST -> transaction -> refreshed table. */
export function createWecomAccount(form) { return request('/api/wecom-accounts', { method: 'POST', body: JSON.stringify(form) }); }

/** Code purpose (plain language): searches company profiles for the registration-subject picker. Related files: WecomAccountView.js, WecomAccountController.java. Data flow: remote select -> GET lookup -> options. */
export function searchCompanyProfiles(keyword) { return request(`/api/wecom-accounts/lookups/company-profiles?keyword=${encodeURIComponent(keyword || '')}`); }

/** Code purpose (plain language): searches existing phone assets for the registration-phone input. Related files: WecomAccountView.js, WecomAccountController.java. Data flow: autocomplete -> GET lookup -> selectable numbers. */
export function searchPhoneAssets(keyword) { return request(`/api/wecom-accounts/lookups/phone-assets?keyword=${encodeURIComponent(keyword || '')}`); }

/** Code purpose (plain language): searches optional WeCom owners. Related files: WecomAccountView.js, WecomAccountController.java. Data flow: remote select -> GET lookup -> options. */
export function searchCompanyPersons(keyword) { return request(`/api/wecom-accounts/lookups/company-persons?keyword=${encodeURIComponent(keyword || '')}`); }
