// src\utils\getAccessToken.ts

export async function getAccessToken() {
  // 从环境变量获取 API URL、partnerID 和 secret
  const url = process.env.NEXT_PUBLIC_API_URL_OAUTH || 'https://sfapi.sf-express.com/oauth2/accessToken';
  const partnerID = process.env.PARTNER_ID || 'defaultPartnerID';
  const secret = process.env.SECRET || 'defaultSecret';

  const formData = new URLSearchParams();
  formData.append('partnerID', partnerID);
  formData.append('secret', secret);
  formData.append('grantType', 'password');

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: formData.toString()
    });

    if (!response.ok) {
      throw new Error(`请求失败: ${response.status}`);
    }

    const data = await response.json();
    return data.accessToken;
  } catch (error) {
    console.error('获取访问令牌时出错:', error);
    throw error; // 抛出错误让调用者处理
  }
}
