import 'dart:convert';

import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:syncrow_app/utils/helpers/decode_base64.dart';

class Token {
  static const String loginAccessTokenKey = 'accessToken';
  static const String loginRefreshTokenKey = 'refreshToken';

  final String accessToken;
  final String refreshToken;

  //{
  //   "email": "test@test.com",
  //   "userId": 3,
  //   "uuid": "563e22d2-cb30-46d3-8c48-fa7d762342f0",
  //   "sessionId": "f76aa067-c915-4921-b04d-9fbc71c4965a",
  //   "iat": 1710137435,
  //   "exp": 1710137735
  // }

  final String sessionId;

  final int iat;
  final int exp;

  Token.emptyConstructor()
      : accessToken = '',
        refreshToken = '',
        sessionId = '',
        iat = 0,
        exp = 0;

  bool get accessTokenIsNotEmpty => accessToken.isNotEmpty;

  bool get refreshTokenIsNotEmpty => refreshToken.isNotEmpty;

  bool get isNotEmpty => accessToken.isNotEmpty && refreshToken.isNotEmpty;

  Token(
    this.accessToken,
    this.refreshToken,
    this.sessionId,
    this.iat,
    this.exp,
  );

  Token.refreshToken(this.refreshToken)
      : accessToken = '',
        sessionId = '',
        iat = 0,
        exp = 0;

  factory Token.fromJson(Map<String, dynamic> json) {
    //save token to secure storage
    var storage = const FlutterSecureStorage();
    storage.write(
        key: loginAccessTokenKey, value: json[loginAccessTokenKey] ?? '');
    storage.write(
        key: loginRefreshTokenKey, value: json[loginRefreshTokenKey] ?? '');
    //create token object ?
    return Token(json[loginAccessTokenKey] ?? '',
        json[loginRefreshTokenKey] ?? '', '', 0, 0);
  }

  Map<String, String> refreshTokenToJson() =>
      {loginRefreshTokenKey: refreshToken};

  Map<String, String> accessTokenToJson() => {loginAccessTokenKey: accessToken};

  static Map<String, dynamic> decodeToken(String accessToken) {
    final parts = accessToken.split('.');
    if (parts.length != 3) {
      throw Exception('invalid access token');
    }
    final payload = decodeBase64(parts[1]);
    return json.decode(payload);
  }
}
