const BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000/api';

export interface UploadResult {
  url: string;
  filename: string;
  originalname: string;
  size: number;
}

export function uploadFile(filePath: string, options?: { useSellerToken?: boolean }): Promise<string> {
  const token = options?.useSellerToken
    ? uni.getStorageSync('sellerToken') || ''
    : uni.getStorageSync('token') || '';

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: `${BASE_URL}/${options?.useSellerToken ? 'seller/' : ''}upload`,
      filePath,
      name: 'file',
      header: token ? { Authorization: `Bearer ${token}` } : {},
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          try {
            const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
            console.log('[upload] response data:', JSON.stringify(data));
            if ((data.code === 0 || data.code === 200 || data.code === 201) && data.data?.url) {
              resolve(data.data.url.startsWith('http') ? data.data.url : `${BASE_URL.replace('/api', '')}${data.data.url}`);
            } else if (data.url) {
              resolve(data.url);
            } else {
              reject(new Error(data.message || '上传失败'));
            }
          } catch (e) {
            console.error('[upload] parse error:', e, 'raw:', res.data);
            reject(new Error('解析响应失败'));
          }
        } else if (res.statusCode === 401) {
          reject(new Error('登录已过期'));
        } else {
          reject(new Error(`上传失败 (${res.statusCode})`));
        }
      },
      fail: (err) => {
        reject(new Error(err.errMsg || '网络异常'));
      },
    });
  });
}

export function chooseAndUpload(options?: {
  count?: number;
  useSellerToken?: boolean;
}): Promise<string[]> {
  return new Promise((resolve, reject) => {
    uni.chooseImage({
      count: options?.count || 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        const urls: string[] = [];
        try {
          for (const path of res.tempFilePaths) {
            const url = await uploadFile(path, { useSellerToken: options?.useSellerToken });
            urls.push(url);
          }
          resolve(urls);
        } catch (err: any) {
          reject(err);
        }
      },
      fail: () => reject(new Error('取消选择图片')),
    });
  });
}
