import { http } from '@kit.NetworkKit';
import { getServerUrl } from './ApiConfig';

export interface AiResultItem {
  category: string;
  message: string;
}

export interface ApiResult {
  code: number;
  msg: string;
  category?: string;
  message?: string;
  aiResult?: AiResultItem;
}

export interface BillItem {
  id: number;
  type: string;
  category: string;
  amount: number;
  message: string;
  remark: string;
  createTime: string;
}

export async function submitBill(
  type: string,
  category: string,
  amount: number,
  remark: string
): Promise<ApiResult> {
  const baseUrl = await getServerUrl();
  const req = http.createHttp();
  try {
    const body = JSON.stringify({ type, category, amount, remark });
    const resp = await req.request(`${baseUrl}/api/bills`, {
      method: http.RequestMethod.POST,
      header: { 'Content-Type': 'application/json' },
      extraData: body,
      connectTimeout: 5000,
      readTimeout: 10000
    });
    if (resp.responseCode === 200) {
      return JSON.parse(resp.result as string) as ApiResult;
    }
    return { code: resp.responseCode, msg: `请求失败: ${resp.responseCode}` };
  } catch (e) {
    return { code: -1, msg: '网络不可用，已保存到本地' };
  } finally {
    req.destroy();
  }
}

export async function aiClassify(
  type: string,
  amount: number,
  remark: string
): Promise<ApiResult> {
  const baseUrl = await getServerUrl();
  const req = http.createHttp();
  try {
    const body = JSON.stringify({ type, amount, remark });
    const resp = await req.request(`${baseUrl}/api/transfer`, {
      method: http.RequestMethod.POST,
      header: { 'Content-Type': 'application/json' },
      extraData: body,
      connectTimeout: 5000,
      readTimeout: 10000
    });
    if (resp.responseCode === 200) {
      return JSON.parse(resp.result as string) as ApiResult;
    }
    return { code: resp.responseCode, msg: `请求失败: ${resp.responseCode}` };
  } catch (e) {
    return { code: -1, msg: '网络不可用，请手动选择分类' };
  } finally {
    req.destroy();
  }
}

export async function fetchBills(type?: string, category?: string): Promise<BillItem[]> {
  const baseUrl = await getServerUrl();
  const req = http.createHttp();
  try {
    let queryUrl = `${baseUrl}/api/bills`;
    const params: string[] = [];
    if (type) params.push(`type=${encodeURIComponent(type)}`);
    if (category) params.push(`category=${encodeURIComponent(category)}`);
    if (params.length > 0) queryUrl += '?' + params.join('&');

    const resp = await req.request(queryUrl, {
      method: http.RequestMethod.GET,
      header: { 'Content-Type': 'application/json' },
      connectTimeout: 5000,
      readTimeout: 10000
    });
    if (resp.responseCode === 200) {
      return JSON.parse(resp.result as string) as BillItem[];
    }
    return [];
  } catch (e) {
    return [];
  } finally {
    req.destroy();
  }
}
