import { get, post } from '@/shared/services/http';

export const PAYMENT_METHODS = {
    Alipay: 'alipay',
    WeChat: 'wechat',
    Mock: "mock"
} as const;

export type PaymentMethod = typeof PAYMENT_METHODS[keyof typeof PAYMENT_METHODS];

export type AvailablePaymentMethod = typeof PAYMENT_METHODS.Alipay;

export interface CreateOrderRequestBody {
    amount_cent: number,
    payment_channel: AvailablePaymentMethod
}

export const PAYMENT_STATUS = {
    Pending: 'pending',   // 待支付
    Paid: 'paid',         // 已支付
    Expired: 'expired',   // 已过期
    Failed: 'failed',     // 支付失败
} as const;

export type PaymentStatus = typeof PAYMENT_STATUS[keyof typeof PAYMENT_STATUS];
// 中文映射表
export const PAYMENT_STATUS_TEXT_MAP: Record<PaymentStatus, string> = {
    [PAYMENT_STATUS.Pending]: '待支付',
    [PAYMENT_STATUS.Paid]: '已支付',
    [PAYMENT_STATUS.Expired]: '已过期',
    [PAYMENT_STATUS.Failed]: '支付失败',
};

// 辅助函数：根据状态获取中文
export function getPaymentStatusText(status: PaymentStatus): string {
    return PAYMENT_STATUS_TEXT_MAP[status];
}

export interface CreateOrderResponseBody {
    id: string,
    user_id: string,
    amount_cent: number,
    status: PaymentStatus,
    payment_channel: AvailablePaymentMethod,
    out_trade_no: string,
    transaction_id: string,
    pay_url: string,
    expires_at: Date,
    paid_at: Date,
    created_at: Date,
}

export interface OrderListRequestParam {
    status?: PaymentStatus,
    page: number,
    page_size: number,
}

// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface OrderListResponseBody extends CreateOrderResponseBody {

}

export interface OrderInfoRequestParam {
    order_id: string,
}

// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface OrderInfoResponseBody extends CreateOrderResponseBody {

}

const PaymentUrlObj = {
    createOrder: "/api/v1/payments/orders",
    getOrderList: "/api/v1/payments/orders",
    getOrderInfo: "/api/v1/payments/orders/{order_id}",
};

// ============================================================
// 调用方式：PaymentAPI.createOrder() / PaymentAPI.getOrdersListInfo() 等
// ============================================================

export class PaymentAPI {
    /** 创建支付订单 */
    static async createOrder(body: CreateOrderRequestBody): Promise<CreateOrderResponseBody> {
        return await post<CreateOrderResponseBody>(PaymentUrlObj.createOrder, body);
    }

    /** 获取订单列表（支持按状态筛选 + 分页） */
    static async getOrdersListInfo(param: OrderListRequestParam, signal?: AbortSignal): Promise<OrderListResponseBody[]> {
        return await get<OrderListResponseBody[]>(PaymentUrlObj.getOrderList, param as unknown as Record<string, unknown>, { signal });
    }

    /** 获取单个订单详情 */
    static async getOrderInfo(param: OrderInfoRequestParam): Promise<OrderInfoResponseBody> {
        const url = PaymentUrlObj.getOrderInfo.replace('{order_id}', param.order_id);
        return await get<OrderInfoResponseBody>(url);
    }
}
