import 'package:flutter_secure_storage/flutter_secure_storage.dart';

import 'jenkins_client.dart';

class JenkinsSessionConfig {
  const JenkinsSessionConfig({
    required this.baseUrl,
    required this.credentials,
  });

  final Uri baseUrl;
  final JenkinsCredentials credentials;
}

class TokenStore {
  TokenStore({FlutterSecureStorage? storage})
    : _storage = storage ?? const FlutterSecureStorage();

  static const _usernameKey = 'jenkins.username';
  static const _apiTokenKey = 'jenkins.apiToken';
  static const _baseUrlKey = 'jenkins.baseUrl';

  final FlutterSecureStorage _storage;

  Future<JenkinsCredentials?> readCredentials() async {
    final username = await _storage.read(key: _usernameKey);
    final apiToken = await _storage.read(key: _apiTokenKey);

    if (username == null || apiToken == null) {
      return null;
    }

    return JenkinsCredentials(username: username, apiToken: apiToken);
  }

  Future<void> saveCredentials(JenkinsCredentials credentials) async {
    await _storage.write(key: _usernameKey, value: credentials.username);
    await _storage.write(key: _apiTokenKey, value: credentials.apiToken);
  }

  Future<void> clearCredentials() async {
    await _storage.delete(key: _usernameKey);
    await _storage.delete(key: _apiTokenKey);
  }

  Future<JenkinsSessionConfig?> readSession() async {
    final baseUrlRaw = await _storage.read(key: _baseUrlKey);
    final username = await _storage.read(key: _usernameKey);
    final apiToken = await _storage.read(key: _apiTokenKey);

    if (baseUrlRaw == null || username == null || apiToken == null) {
      return null;
    }

    final baseUrl = Uri.tryParse(baseUrlRaw);
    if (baseUrl == null) {
      return null;
    }

    return JenkinsSessionConfig(
      baseUrl: baseUrl,
      credentials: JenkinsCredentials(username: username, apiToken: apiToken),
    );
  }

  Future<void> saveSession(JenkinsSessionConfig session) async {
    await _storage.write(key: _baseUrlKey, value: session.baseUrl.toString());
    await _storage.write(
      key: _usernameKey,
      value: session.credentials.username,
    );
    await _storage.write(
      key: _apiTokenKey,
      value: session.credentials.apiToken,
    );
  }

  Future<void> clearSession() async {
    await _storage.delete(key: _baseUrlKey);
    await _storage.delete(key: _usernameKey);
    await _storage.delete(key: _apiTokenKey);
  }
}
