import { storeAuthTokens } from "@/constants/token";
import type { OAuthTokenResponse } from "@/constants/token";
import { getRequestContext, request, requestRaw } from "../utils/request";

// 获取oauth token
export interface OauthTokenRequest {
  grant_type?: string;
  idToken?: string[];
  scope?: string;
  mobile?: string;
  code?: string;
  clientConfigId?: string;
  [property: string]: any;
}

export function buildFormUrlEncodedParams(
  data: Record<string, unknown>,
): URLSearchParams {
  const params = new URLSearchParams();
  Object.entries(data).forEach(([key, value]) => {
    if (value === undefined || value === null) return;
    if (Array.isArray(value)) {
      value.forEach((item) => {
        if (item === undefined || item === null) return;
        params.append(key, String(item));
      });
      return;
    }
    params.append(key, String(value));
  });
  return params;
}

export async function oauthToken(
  data: OauthTokenRequest,
): Promise<OAuthTokenResponse> {
  const params = buildFormUrlEncodedParams({
    ...data,
    clientId: data.clientId ?? getRequestContext().clientId ?? "6",
    clientConfigId: data.clientConfigId ?? getRequestContext().clientId ?? "6",
  } as Record<string, unknown>);

  const res = await requestRaw<OAuthTokenResponse>(
    {
      url: "/auth/oauth2/token",
      method: "post",
      data: params,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        Authorization: "Basic Y3VzdG9tOmN1c3RvbQ==",
      },
    },
    { skipAuth: true },
  );

  storeAuthTokens(res, {
    requireRefreshToken: data.grant_type !== "refresh_token",
  });

  return res;
}

// 发送手机验证码
export function sendCode(mobile: string) {
  const value = (mobile ?? "").trim();
  const encoded = encodeURIComponent(value);

  return request(
    {
      url: `/admin/platformUser/sendMobileCode/${encoded}`,
      method: "get",
    },
    {
      skipAuth: true,
      headers: {
        clientConfigId: getRequestContext().clientId ?? "",
      },
    },
  );
}

// 检测用户是否绑定手机号
export function checkUserPhone(args: any) {
  return request({
    url: "/hotelBiz/user/checkUserHasBindPhone",
    method: "get",
    params: args,
  });
}

// 获取登录用户手机号
export function getLoginUserPhone(args: any) {
  return request({
    url: "/hotelBiz/user/getLoginUserPhone",
    method: "get",
    params: args,
  });
}

// 获取服务协议
export function getServiceAgreement(args: any) {
  return request({
    url: "/hotelBiz/mainScene/serviceAgreement",
    method: "get",
    params: args,
  });
}

// 获取隐私协议
export function getPrivacyAgreement(args: any) {
  return request({
    url: "/hotelBiz/mainScene/privacyPolicy",
    method: "get",
    params: args,
  });
}
