import 'package:nextcloud/nextcloud.dart';

import '../../../model/account_data.dart';
import '../../../model/endpoint_data.dart';
import '../../api_response.dart';

abstract class WebdavApi<T> {
  T genericParams;

  WebdavApi(this.genericParams);

  Future<ApiResponse> run();

  static Future<WebDavClient>? _webdav;
  static String? _webdavSecret;

  /// Shared WebDAV client. Rebuilt whenever the effective Nextcloud secret
  /// changes (app password minted/renewed, account switch) so it never keeps
  /// authenticating with stale credentials.
  static Future<WebDavClient> get webdav {
    final secret = AccountData().getNextcloudSecret();
    if (_webdav == null || _webdavSecret != secret) {
      _webdavSecret = secret;
      _webdav = establishWebdavConnection();
    }
    return _webdav!;
  }

  static Future<WebDavClient> establishWebdavConnection() async =>
      NextcloudClient(
        Uri.parse('https://${EndpointData().nextcloud().full()}'),
        // App password preferred — with 2FA the real password is not accepted
        // by Nextcloud at all (see AccountData.usesLoginFlow).
        password: AccountData().getNextcloudSecret(),
        loginName: AccountData().getUsername(),
      ).webdav;

  /// Builds the WebDAV download URL without embedded credentials. Callers must
  /// authenticate via the [AccountData.authHeaders] header instead.
  static String buildWebdavUrl() =>
      'https://${EndpointData().nextcloud().full()}/remote.php/dav/files/${AccountData().getUsername()}/';
}
