import 'package:dio/dio.dart';

import '../../auth/token_storage.dart';
import '../../marianumconnect_api.dart';
import '../../marianumconnect_query.dart';
import 'auth_login_response.dart';

/// Performs the Marianum-Connect bearer login. Used both by the foreground
/// login flow and by the auth interceptor's silent re-auth on 401. Does *not*
/// run through the shared dio instance — that one has the interceptor, which
/// would attempt to re-auth us into a loop if our credentials are wrong.
class AuthLogin extends MarianumConnectQuery {
  final MarianumConnectTokenStorage _tokenStorage;

  AuthLogin({
    MarianumConnectTokenStorage tokenStorage =
        const MarianumConnectTokenStorage(),
    Dio? dio,
  }) : _tokenStorage = tokenStorage,
       super(dio: dio ?? MarianumConnectApi.plainDio());

  Future<AuthLoginResponse> run({
    required String username,
    required String password,
    required String tokenName,
  }) => guard(() async {
    final response = await dio.post<Map<String, dynamic>>(
      endpoint('auth/login'),
      data: {
        'username': username,
        'password': password,
        'tokenName': tokenName,
      },
    );
    final payload = AuthLoginResponse.fromJson(response.data!);
    await _tokenStorage.write(
      token: payload.token,
      tokenId: payload.tokenId,
      expiresAt: payload.expiresAt,
    );
    return payload;
  });
}
