import pool from '../config/database';

export interface AppSetting {
  key: string;
  value: any;
  updated_at: string;
  updated_by: string | null;
}

class SettingsService {
  async getAll(): Promise<AppSetting[]> {
    const result = await pool.query('SELECT * FROM app_settings ORDER BY key');
    return result.rows;
  }

  async get(key: string): Promise<AppSetting | null> {
    const result = await pool.query('SELECT * FROM app_settings WHERE key = $1', [key]);
    return result.rows[0] ?? null;
  }

  async set(key: string, value: any, userId: string): Promise<AppSetting> {
    const result = await pool.query(
      `INSERT INTO app_settings (key, value, updated_by, updated_at)
       VALUES ($1, $2, $3, NOW())
       ON CONFLICT (key) DO UPDATE SET value = $2, updated_by = $3, updated_at = NOW()
       RETURNING *`,
      [key, JSON.stringify(value), userId]
    );
    return result.rows[0];
  }

  async delete(key: string): Promise<boolean> {
    const result = await pool.query('DELETE FROM app_settings WHERE key = $1', [key]);
    return (result.rowCount ?? 0) > 0;
  }

  async getExternalLinks(): Promise<Array<{id: string; name: string; links: Array<{name: string; url: string}>}>> {
    const setting = await this.get('external_links');
    const value = setting?.value;
    if (!Array.isArray(value)) return [];

    // Already in LinkCollection[] format
    if (value.length === 0) return [];
    if (value[0] && 'links' in value[0]) return value;

    // Old flat format: Array<{name, url}> — migrate to single collection
    const migrated = [{ id: 'default', name: 'Links', links: value }];
    // Persist migrated format (use system user id)
    await this.set('external_links', migrated, 'system');
    return migrated;
  }
}

export default new SettingsService();
