import {
  MOCK_ACCOUNTS,
  MOCK_BUDGETS,
  MOCK_CATEGORIES,
  MOCK_CURRENCIES,
  MOCK_EXCHANGE_RATES,
} from './mock-data';
import db from './sqlite';

export function listAccounts() {
  return MOCK_ACCOUNTS;
}

export function listCategories() {
  // 从数据库读取分类
  try {
    const stmt = db.prepare(`
      SELECT id, name, type, icon, color, user_id as userId, is_active as isActive
      FROM finance_categories
      WHERE is_active = 1
      ORDER BY type, id
    `);
    const categories = stmt.all() as any[];
    
    // 转换为前端需要的格式
    return categories.map(cat => ({
      id: cat.id,
      userId: cat.userId,
      name: cat.name,
      type: cat.type,
      icon: cat.icon,
      color: cat.color,
      sortOrder: cat.id,
      isSystem: true,
      isActive: Boolean(cat.isActive),
    }));
  } catch (error) {
    console.error('从数据库读取分类失败，使用MOCK数据:', error);
    return MOCK_CATEGORIES;
  }
}

export function listBudgets() {
  return MOCK_BUDGETS;
}

export function listCurrencies() {
  return MOCK_CURRENCIES;
}

export function listExchangeRates() {
  return MOCK_EXCHANGE_RATES;
}

export function createCategoryRecord(category: any) {
  try {
    const stmt = db.prepare(`
      INSERT INTO finance_categories (name, type, icon, color, user_id, is_active)
      VALUES (?, ?, ?, ?, ?, 1)
    `);
    const result = stmt.run(
      category.name,
      category.type,
      category.icon || '📝',
      category.color || '#dfe4ea',
      category.userId || 1
    );
    return {
      id: result.lastInsertRowid,
      ...category,
      createdAt: new Date().toISOString(),
    };
  } catch (error) {
    console.error('创建分类失败:', error);
    return null;
  }
}

export function updateCategoryRecord(id: number, category: any) {
  try {
    const updates: string[] = [];
    const params: any[] = [];
    
    if (category.name) {
      updates.push('name = ?');
      params.push(category.name);
    }
    if (category.icon) {
      updates.push('icon = ?');
      params.push(category.icon);
    }
    if (category.color) {
      updates.push('color = ?');
      params.push(category.color);
    }
    
    if (updates.length === 0) return null;
    
    params.push(id);
    const stmt = db.prepare(`
      UPDATE finance_categories
      SET ${updates.join(', ')}
      WHERE id = ?
    `);
    stmt.run(...params);
    
    // 返回更新后的分类
    const selectStmt = db.prepare('SELECT * FROM finance_categories WHERE id = ?');
    return selectStmt.get(id);
  } catch (error) {
    console.error('更新分类失败:', error);
    return null;
  }
}

export function deleteCategoryRecord(id: number) {
  try {
    // 软删除
    const stmt = db.prepare(`
      UPDATE finance_categories
      SET is_active = 0
      WHERE id = ?
    `);
    stmt.run(id);
    return true;
  } catch (error) {
    console.error('删除分类失败:', error);
    return false;
  }
}
