// ============================================================
// infrastructure/storage/order-store.ts — 订单记录本地存储
// ============================================================

import { execute, queryAll, queryOne } from '../core/db-core';
import { getCurrentUserId } from '../services/user-scope';
import type { OrderRecordEntry, OrderType, OrderQueryFilter } from '../core/types';
import { logger } from '@/shared/utils/bus';

// ---------- 通用接口 ----------

interface OrderLike {
  id: string;
  status: string;
  created_at?: string | Date;
}

// ---------- API ----------

export function upsertOrder<T extends OrderLike>(orderType: OrderType, order: T): void {
  const now = Date.now();
  const row: OrderRecordEntry = {
    id: order.id,
    user_id: getCurrentUserId(),
    order_type: orderType,
    status: order.status,
    data_json: JSON.stringify(order),
    created_at: typeof order.created_at === 'string'
      ? Date.parse(order.created_at)
      : (order.created_at instanceof Date ? order.created_at.getTime() : now),
  };
  execute(
    `INSERT OR REPLACE INTO order_records (id, user_id, order_type, status, data_json, created_at)
     VALUES (?, ?, ?, ?, ?, ?)`,
    [row.id, row.user_id, row.order_type, row.status, row.data_json, row.created_at],
  );
}

export function syncRechargeOrders<T extends OrderLike>(orders: T[]): number {
  let n = 0;
  for (const o of orders) {
    try { upsertOrder('recharge', o); n++; } catch { /* skip */ }
  }
  logger.debug('storage', `充值订单同步：${n}/${orders.length}`);
  return n;
}

export function syncVipOrders<T extends OrderLike>(orders: T[]): number {
  let n = 0;
  for (const o of orders) {
    try { upsertOrder('vip', o); n++; } catch { /* skip */ }
  }
  logger.debug('storage', `VIP 订单同步：${n}/${orders.length}`);
  return n;
}

export function getOrders<T extends OrderLike>(filter: OrderQueryFilter = {}): T[] {
  const uid = getCurrentUserId();
  let rows: OrderRecordEntry[];
  if (filter.order_type) {
    rows = queryAll<OrderRecordEntry>(
      `SELECT * FROM order_records WHERE user_id = ? AND order_type = ? ORDER BY created_at DESC LIMIT ?`,
      [uid, filter.order_type, filter.limit || 100],
    );
  } else {
    rows = queryAll<OrderRecordEntry>(
      `SELECT * FROM order_records WHERE user_id = ? ORDER BY created_at DESC LIMIT ?`,
      [uid, filter.limit || 100],
    );
  }
  return rows.map(r => {
    try { return JSON.parse(r.data_json) as T; } catch { return { id: r.id, status: r.status } as unknown as T; }
  });
}

export function getOrderById<T extends OrderLike>(orderId: string): T | null {
  const row = queryOne<OrderRecordEntry>(`SELECT * FROM order_records WHERE id = ?`, [orderId]);
  if (!row) return null;
  try { return JSON.parse(row.data_json) as T; } catch { return null; }
}

export function deleteOrder(orderId: string): void {
  execute(`DELETE FROM order_records WHERE id = ?`, [orderId]);
}

export function getOrderCount(orderType?: OrderType): number {
  const uid = getCurrentUserId();
  if (orderType) {
    const row = queryOne<{ cnt: number }>(
      `SELECT COUNT(*) as cnt FROM order_records WHERE user_id = ? AND order_type = ?`,
      [uid, orderType],
    );
    return row?.cnt ?? 0;
  }
  const row = queryOne<{ cnt: number }>(
    `SELECT COUNT(*) as cnt FROM order_records WHERE user_id = ?`,
    [uid],
  );
  return row?.cnt ?? 0;
}

export function clearUserOrders(): void {
  execute(`DELETE FROM order_records WHERE user_id = ?`, [getCurrentUserId()]);
}
