import { getDatabase } from '../index';
import { Settings } from '../../../types';

export async function getSettings(userId: string): Promise<Settings> {
  const db = getDatabase();
  const row = await db.getFirstAsync<any>(
    'SELECT * FROM settings WHERE user_id = ?',
    [userId]
  );

  if (!row) {
    // Create default settings for this user
    const defaults: Settings = {
      unitSystem: 'imperial',
      tempUnit: 'F',
      weightUnit: 'lb',
      analyticsOptIn: false,
    };

    await db.runAsync(
      `INSERT INTO settings (user_id, unit_system, temp_unit, weight_unit, analytics_opt_in)
       VALUES (?, ?, ?, ?, ?)`,
      [userId, defaults.unitSystem, defaults.tempUnit, defaults.weightUnit, defaults.analyticsOptIn ? 1 : 0]
    );

    return defaults;
  }

  return {
    unitSystem: row.unit_system,
    tempUnit: row.temp_unit,
    weightUnit: row.weight_unit || 'lb',
    analyticsOptIn: row.analytics_opt_in === 1,
  };
}

export async function updateSettings(userId: string, updates: Partial<Settings>): Promise<void> {
  const db = getDatabase();
  const current = await getSettings(userId);
  const updated = { ...current, ...updates };

  await db.runAsync(
    `UPDATE settings
     SET unit_system = ?, temp_unit = ?, weight_unit = ?, analytics_opt_in = ?
     WHERE user_id = ?`,
    [
      updated.unitSystem,
      updated.tempUnit,
      updated.weightUnit,
      updated.analyticsOptIn ? 1 : 0,
      userId,
    ]
  );
}
