import Taro from "@tarojs/taro";
import { apiRequest, normalizeMessage } from "./client";

const BASE_URL = __API_BASE__;

export function sendSmsCode(phone: string) {
  return apiRequest("/api/auth/login/code/send", {
    method: "POST",
    data: { identifier: phone, accountType: "user" }
  });
}

export function smsLogin(phone: string, code: string) {
  return apiRequest("/api/auth/login/code/verify", {
    method: "POST",
    data: { identifier: phone, code, accountType: "user" }
  });
}

export function passwordLogin(identifier: string, password: string) {
  return apiRequest("/api/auth/login/password", {
    method: "POST",
    data: { identifier, password, accountType: "user" }
  });
}

export function wechatMiniSession(code: string) {
  return apiRequest("/api/auth/wechat/mini/session", {
    method: "POST",
    data: { code }
  });
}

export function pcQrScan(loginId: string) {
  return apiRequest(`/api/auth/wechat/pc-qr/${encodeURIComponent(loginId)}/scan`, {
    method: "POST"
  });
}

export function pcQrConfirm(loginId: string, code: string) {
  return apiRequest(`/api/auth/wechat/pc-qr/${encodeURIComponent(loginId)}/confirm`, {
    method: "POST",
    data: { code }
  });
}

export function pcQrCompleteOnboarding(loginId: string, onboardingToken: string) {
  return apiRequest(`/api/auth/wechat/pc-qr/${encodeURIComponent(loginId)}/complete-onboarding`, {
    method: "POST",
    header: onboardingHeaders(onboardingToken)
  });
}

function onboardingHeaders(onboardingToken: string) {
  return { "X-Onboarding-Token": onboardingToken };
}

export function onboardingStatus(onboardingToken: string) {
  return apiRequest("/api/auth/onboarding/status", {
    header: onboardingHeaders(onboardingToken)
  });
}

export function onboardingSendSmsCode(onboardingToken: string, phone: string) {
  return apiRequest("/api/auth/onboarding/send-sms-code", {
    method: "POST",
    header: onboardingHeaders(onboardingToken),
    data: { phone }
  });
}

export function onboardingBindPhone(onboardingToken: string, phone: string, code: string) {
  return apiRequest("/api/auth/onboarding/bind-phone", {
    method: "POST",
    header: onboardingHeaders(onboardingToken),
    data: { phone, code }
  });
}

export function onboardingEmail(onboardingToken: string, email: string) {
  return apiRequest("/api/auth/onboarding/email", {
    method: "POST",
    header: onboardingHeaders(onboardingToken),
    data: { email }
  });
}

export function onboardingSendEmailCode(onboardingToken: string, email: string) {
  return apiRequest("/api/auth/onboarding/send-email-code", {
    method: "POST",
    header: onboardingHeaders(onboardingToken),
    data: { email }
  });
}

export function onboardingVerifyEmail(onboardingToken: string, email: string, code: string) {
  return apiRequest("/api/auth/onboarding/verify-email", {
    method: "POST",
    header: onboardingHeaders(onboardingToken),
    data: { email, code }
  });
}

export function onboardingSetPassword(onboardingToken: string, password: string) {
  return apiRequest("/api/auth/onboarding/set-password", {
    method: "POST",
    header: onboardingHeaders(onboardingToken),
    data: { password }
  });
}

export function onboardingProfile(onboardingToken: string, payload: Record<string, any>) {
  return apiRequest("/api/auth/onboarding/profile", {
    method: "POST",
    header: onboardingHeaders(onboardingToken),
    data: payload
  });
}

export function onboardingInterests(onboardingToken: string, labelItemIds: number[]) {
  return apiRequest("/api/auth/onboarding/interests", {
    method: "POST",
    header: onboardingHeaders(onboardingToken),
    data: { labelItemIds, customLabels: [], scope: "interest" }
  });
}

export function onboardingMemberApplication(onboardingToken: string, payload: Record<string, any>) {
  return apiRequest("/api/auth/onboarding/member-application", {
    method: "POST",
    header: onboardingHeaders(onboardingToken),
    data: payload
  });
}

export function onboardingComplete(onboardingToken: string) {
  return apiRequest("/api/auth/onboarding/complete", {
    method: "POST",
    header: onboardingHeaders(onboardingToken)
  });
}

export async function onboardingUploadFile(
  onboardingToken: string,
  filePath: string,
  name = "file",
  options: { visibility?: "public" | "private"; businessType?: string; originalName?: string } = {}
) {
  const query = new URLSearchParams();
  query.set("visibility", options.visibility || "private");
  query.set("businessType", options.businessType || "member_application");
  if (options.originalName) query.set("originalName", options.originalName);
  const response = await Taro.uploadFile({
    url: `${BASE_URL}/api/auth/onboarding/upload?${query.toString()}`,
    filePath,
    name,
    header: onboardingHeaders(onboardingToken)
  });
  let body: any = response.data;
  if (typeof body === "string") {
    try {
      body = JSON.parse(body);
    } catch {
      body = null;
    }
  }
  if (response.statusCode < 200 || response.statusCode >= 300 || !body || body.code !== 0) {
    const msg = normalizeMessage(body?.message || `上传失败(${response.statusCode})`, body?.code);
    Taro.showToast({ title: msg, icon: "none" });
    throw new Error(msg);
  }
  return body.data;
}
