import Taro from "@tarojs/taro";
import { normalizeMessage } from "../api/client";
import { getToken } from "./auth";
import { getAdminToken } from "./adminAuth";

const BASE_URL = __API_BASE__;

type UploadOptions = {
  tokenType?: "user" | "admin";
  originalName?: string;
};

export async function uploadFileToBackend(filePath: string, businessType = "temp", options: UploadOptions = {}) {
  const token = options.tokenType === "admin" ? getAdminToken() : getToken();
  if (!token) {
    throw new Error(options.tokenType === "admin" ? "ADMIN_UNAUTHORIZED" : "UNAUTHORIZED");
  }
  const formData: Record<string, string> = {
    businessType,
    visibility: businessType === "member_application" || businessType === "member_application_photo" ? "private" : "public"
  };
  if (options.originalName) {
    formData.originalName = options.originalName;
  }

  const res = await Taro.uploadFile({
    url: `${BASE_URL}/api/files/upload`,
    filePath,
    name: "file",
    header: {
      Authorization: `Bearer ${token}`
    },
    formData
  });

  let body = null;
  try {
    body = JSON.parse(res.data || "{}");
  } catch (e) {
    throw new Error("上传响应解析失败");
  }

  if (!body || body.code !== 0) {
    throw new Error(normalizeMessage(body?.message || "上传失败"));
  }
  return body.data;
}

export function uploadImageToBackend(filePath: string, businessType = "temp", options: UploadOptions = {}) {
  return uploadFileToBackend(filePath, businessType, options);
}
