import 'dart:convert';

import 'package:pocketbase/pocketbase.dart';
import 'package:shared_preferences/shared_preferences.dart';

const _kAuthKey = 'pb_auth';
const _kRememberSessionKey = 'remember_session';

class PocketBaseClient {
  PocketBaseClient._({
    required this.pb,
    required SharedPreferences prefs,
    required bool rememberSession,
  })  : _prefs = prefs,
        _rememberSession = rememberSession;
  static PocketBaseClient? _instance;
  static PocketBaseClient get instance => _instance!;
  final PocketBase pb;
  final SharedPreferences _prefs;
  bool _rememberSession;

  bool get rememberSession => _rememberSession;

  static Future<void> init() async {
    final prefs = await SharedPreferences.getInstance();
    final remember = prefs.getBool(_kRememberSessionKey) ?? true;
    final stored = prefs.getString(_kAuthKey);

    final store = AsyncAuthStore(
      save: (String data) async {
        final client = _instance;
        if (client == null || client._rememberSession) {
          await prefs.setString(_kAuthKey, data);
          return;
        }
        await prefs.remove(_kAuthKey);
      },
      initial: remember ? stored : null,
    );

    _instance = PocketBaseClient._(
      pb: PocketBase('https://pocket.kovaksoft.com', authStore: store),
      prefs: prefs,
      rememberSession: remember,
    );

    if (!remember && stored != null) {
      await prefs.remove(_kAuthKey);
    }
  }

  Future<void> setRememberSession(bool value) async {
    _rememberSession = value;
    await _prefs.setBool(_kRememberSessionKey, value);
    if (!value) {
      await _prefs.remove(_kAuthKey);
    } else if (pb.authStore.isValid) {
      await _prefs.setString(
        _kAuthKey,
        jsonEncode({
          'token': pb.authStore.token,
          'model': pb.authStore.record,
        }),
      );
    }
  }
}
