// 地址服务 - 对应 supermart-mini/service/address.js
import { get, postL } from './http';

const apis = {
  LIST: '/api/addressBook',
  ADD: '/api/addressBook/add',
  DELETE: '/api/addressBook/delete',
  DEFAULT: '/api/addressBook/getDefault',
  UPDATE: '/api/addressBook/update',
  UPDATE_ORDER_ADDRESS: '/api/mallOrder/updateAddress',
  GET_AREA: '/api/area',
};

export interface Address {
  id: string;
  contactName: string;
  contactNo: string;
  province: string;
  city: string;
  district: string;
  address: string;
  location?: string;
  defaultFlag?: number;
}

export interface AddAddressParams {
  contactName: string;
  contactNo: string;
  province: string;
  city: string;
  district?: string;
  address: string;
  location?: string;
  defaultFlag?: number;
}

export interface AreaItem {
  id: string;
  name: string;
  pid?: number;
}

// 获取默认地址
export const getDefaultAddress = async (): Promise<Address | null> => {
  const res = await get<Address>(apis.DEFAULT);
  if (res.data && res.data.id) {
    return res.data;
  }
  return null;
};

// 获取地址列表
export const getAddressList = async (size = 100): Promise<Address[]> => {
  const res = await get<Address[]>(apis.LIST, { size });
  // API returns array directly in data
  return Array.isArray(res.data) ? res.data : (res.data as any)?.records || [];
};

// 添加地址
export const addAddress = async (params: AddAddressParams): Promise<boolean> => {
  const res = await postL(apis.ADD, {
    ...params,
    district: params.district || '',
  });
  return res.success;
};

// 删除地址
export const deleteAddress = async (id: string): Promise<boolean> => {
  const res = await postL(`${apis.DELETE}/${id}`);
  return res.success;
};

// 更新地址（设为默认）
export const updateAddress = async (address: Address): Promise<boolean> => {
  const res = await postL(apis.UPDATE, address);
  return res.success;
};

// 更新订单地址
export const updateOrderAddress = async (params: { tradeNo: string; addressBookId: string }) => {
  const res = await postL(apis.UPDATE_ORDER_ADDRESS, params);
  return res;
};

// 获取地区数据
export const getArea = async (pid?: number): Promise<AreaItem[]> => {
  const params = pid !== undefined ? { pid } : { pid: 0 }; // Default to 0 if undefined, allow 0 if passed
  const res = await get<AreaItem[]>(apis.GET_AREA, params);
  return res.data || [];
};

export default {
  getDefaultAddress,
  getAddressList,
  addAddress,
  deleteAddress,
  updateAddress,
  updateOrderAddress,
  getArea,
};
