import request from '@/utils/request';
import type { ApiResult, PageResult } from '@/api';
import type { GltUserTicket, GltUserTicketParam } from './model';

function normalizeTotal(input: unknown): number {
  if (typeof input === 'number' && Number.isFinite(input)) return input;
  if (typeof input === 'string') {
    const n = Number(input);
    if (Number.isFinite(n)) return n;
  }
  if (input && typeof input === 'object') {
    const obj: any = input;
    // Common shapes from different backends.
    for (const key of ['total', 'count', 'value', 'num', 'ticketTotal', 'totalQty']) {
      const v = obj?.[key];
      const n = normalizeTotal(v);
      if (n) return n;
    }
    // Sometimes nested: { data: { total: ... } } / { data: 12 }
    if ('data' in obj) {
      const n = normalizeTotal(obj.data);
      if (n) return n;
    }
  }
  return 0;
}

/**
 * 分页查询我的水票
 */
export async function pageGltUserTicket(params: GltUserTicketParam) {
  const res = await request.get<ApiResult<PageResult<GltUserTicket>>>(
    '/glt/glt-user-ticket/page',
    params
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 查询我的水票列表
 */
export async function listGltUserTicket(params?: GltUserTicketParam) {
  const res = await request.get<ApiResult<GltUserTicket[]>>(
    '/glt/glt-user-ticket',
    params
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 添加我的水票
 */
export async function addGltUserTicket(data: GltUserTicket) {
  const res = await request.post<ApiResult<unknown>>(
    '/glt/glt-user-ticket',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 修改我的水票
 */
export async function updateGltUserTicket(data: GltUserTicket) {
  const res = await request.put<ApiResult<unknown>>(
    '/glt/glt-user-ticket',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 删除我的水票
 */
export async function removeGltUserTicket(id?: number) {
  const res = await request.del<ApiResult<unknown>>(
    '/glt/glt-user-ticket/' + id
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 批量删除我的水票
 */
export async function removeBatchGltUserTicket(data: (number | undefined)[]) {
  const res = await request.del<ApiResult<unknown>>(
    '/glt/glt-user-ticket/batch',
    {
      data
    }
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 根据id查询我的水票
 */
export async function getGltUserTicket(id: number) {
  const res = await request.get<ApiResult<GltUserTicket>>(
    '/glt/glt-user-ticket/' + id
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 获取我的水票总数
 */
export async function getMyGltUserTicketTotal(userId?: number) {
  const params = userId ? { userId } : undefined

  const extract = (res: any) => {
    // Some backends may return a raw number instead of ApiResult.
    if (typeof res === 'number' || typeof res === 'string') return normalizeTotal(res)
    if (res && typeof res === 'object' && 'code' in res) {
      const apiRes = res as ApiResult<unknown>
      if (apiRes.code === 0) return normalizeTotal(apiRes.data)
      throw new Error(apiRes.message)
    }
    return normalizeTotal(res)
  }

  // Try both the configured BaseUrl host and the auth-server host.
  // If the first one returns 0, keep trying; some tenants deploy GLT on a different host.
  const urls = [
    '/glt/glt-user-ticket/my-total'
  ]

  let lastError: unknown
  let firstTotal: number | undefined
  for (const url of urls) {
    try {
      const res = await request.get<any>(url, params)
      if (process.env.NODE_ENV === 'development') {
        console.log('[getMyGltUserTicketTotal] response:', { url, res })
      }
      const total = extract(res)
      if (firstTotal === undefined) firstTotal = total
      if (total) return total
    } catch (e) {
      if (process.env.NODE_ENV === 'development') {
        console.warn('[getMyGltUserTicketTotal] failed:', { url, error: e })
      }
      lastError = e
    }
  }

  if (firstTotal !== undefined) return firstTotal
  return Promise.reject(lastError instanceof Error ? lastError : new Error('获取水票总数失败'))
}
