import 'package:pshared/api/responses/login_pending.dart';
import 'package:pshared/api/responses/token.dart';
import 'package:pshared/data/mapper/account/account.dart';
import 'package:pshared/models/account/account.dart';
import 'package:pshared/models/session_identifier.dart';


class PendingLogin {
  final Account account;
  final TokenData pendingToken;
  final String target;
  final SessionIdentifier session;

  final int? ttlSeconds;
  final int? cooldownSeconds;
  final DateTime? cooldownUntil;
  final String? idempotencyKey;

  const PendingLogin({
    required this.account,
    required this.pendingToken,
    required this.target,
    this.ttlSeconds,
    required this.session,
    this.cooldownSeconds,
    this.cooldownUntil,
    this.idempotencyKey,
  });

  factory PendingLogin.fromResponse(
    PendingLoginResponse response, {
    required SessionIdentifier session,
  }) => PendingLogin(
    account: response.account.account.toDomain(),
    pendingToken: response.pendingToken,
    target: response.target,
    session: session,
  );

  PendingLogin copyWith({
    Account? account,
    TokenData? pendingToken,
    String? target,
    int? ttlSeconds,
    SessionIdentifier? session,
    int? cooldownSeconds,
    DateTime? cooldownUntil,
    bool clearCooldown = false,
    String? idempotencyKey,
  }) {
    return PendingLogin(
      account: account ?? this.account,
      pendingToken: pendingToken ?? this.pendingToken,
      target: target ?? this.target,
      ttlSeconds: ttlSeconds ?? this.cooldownSeconds,
      session: session ?? this.session,
      cooldownSeconds: clearCooldown ? null : cooldownSeconds ?? this.cooldownSeconds,
      cooldownUntil: clearCooldown ? null : cooldownUntil ?? this.cooldownUntil,
      idempotencyKey: idempotencyKey ?? this.idempotencyKey,
    );
  }

  int get cooldownRemainingSeconds {
    final remaining = cooldownUntil?.difference(DateTime.now()).inSeconds ?? 0;
    return remaining < 0 ? 0 : remaining;
  }
}
