import 'dart:async';
import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

import '../../../shared/utils/async_lock.dart';

class SearchHistoryStore {
  static const _key = 'smplayer.search_history';
  static const int _maxItems = 30;


  final AsyncLock _lock = AsyncLock();

  Future<List<String>> list() async {
    final prefs = await SharedPreferences.getInstance();
    return _read(prefs);
  }

  Future<void> add(String keyword) {
    final trimmed = keyword.trim();
    if (trimmed.isEmpty) return Future<void>.value();
    return _lock.run(() async {
      final prefs = await SharedPreferences.getInstance();
      final history = await _read(prefs);
      history
        ..remove(trimmed)
        ..insert(0, trimmed);
      if (history.length > _maxItems) {
        history.removeRange(_maxItems, history.length);
      }
      await prefs.setStringList(_key, history);
    });
  }

  Future<void> remove(String keyword) {
    return _lock.run(() async {
      final prefs = await SharedPreferences.getInstance();
      final history = await _read(prefs)
        ..remove(keyword);
      await prefs.setStringList(_key, history);
    });
  }

  Future<void> clear() {
    return _lock.run(() async {
      final prefs = await SharedPreferences.getInstance();
      await prefs.remove(_key);
    });
  }

  Future<List<String>> _read(SharedPreferences prefs) async {
    final raw = prefs.get(_key);
    if (raw is List) return raw.whereType<String>().toList();
    if (raw is! String || raw.isEmpty) return <String>[];

    try {
      final decoded = jsonDecode(raw);
      if (decoded is! List) return <String>[];
      final history = decoded.whereType<String>().toList();
      await prefs.setStringList(_key, history);
      return history;
    } catch (_) {
      return <String>[];
    }
  }
}
