import 'dart:convert';

import 'package:siro_rider/constant/box_name.dart';
import 'package:siro_rider/constant/info.dart';
import 'package:siro_rider/controller/auth/login_controller.dart';
import 'package:jwt_decoder/jwt_decoder.dart';

import '../../constant/links.dart';
import '../../main.dart';
import 'crud.dart';
import 'encrypt_decrypt.dart';

class SecureStorage {
  void saveData(String key, value) async {
    await storage.write(key: key, value: value);
  }

  Future<String?> readData(String boxName) async {
    final String? value = await storage.read(key: boxName);
    return value.toString();
  }
}

class AppInitializer {
  List<Map<String, dynamic>> links = [];

  /// تقرأ JWT من FlutterSecureStorage أولاً، مع fallback إلى GetStorage
  Future<String?> _readJwt() async {
    try {
      final secureJwt = await storage.read(key: 'jwt');
      if (secureJwt != null && secureJwt.isNotEmpty) return secureJwt;
    } catch (_) {}
    return box.read(BoxName.jwt);
  }

  Future<void> initializeApp() async {
    final jwt = await _readJwt();
    if (jwt == null) {
      await LoginController().getJWT();
    } else {
      bool isTokenExpired =
          JwtDecoder.isExpired(r(jwt).toString().split(AppInformation.addd)[0]);

      if (isTokenExpired) {
        await LoginController().getJWT();
      }
    }

    // await getKey();
  }

  getAIKey(String key1) async {
    if (box.read(BoxName.firstTimeLoadKey) == null) {
      var res =
          await CRUD().get(link: AppLink.getapiKey, payload: {"keyName": key1});
      if (res != 'failure') {
        var d = jsonDecode(res)['message'];
        storage.write(key: key1, value: d[key1].toString());
      } else {}
    }
  }

  Future<void> getKey() async {
    try {
      var res =
          await CRUD().get(link: AppLink.getLocationAreaLinks, payload: {});
      if (res != 'failure') {
        links = List<Map<String, dynamic>>.from(jsonDecode(res)['message']);
        await box.remove(BoxName.locationName);
        await box.remove(BoxName.basicLink);
        await box.remove(links[4]['name']);
        await box.remove(links[1]['name']);
        await box.remove(links[2]['name']);
        await box.write(BoxName.locationName, links);
        await box.write(BoxName.basicLink, (links[0]['server_link']));
        await box.write(links[2]['name'], (links[2]['server_link']));
        await box.write(links[1]['name'], (links[3]['server_link']));
        await box.write(links[3]['name'], (links[1]['server_link']));
        await box.write(BoxName.paymentLink, (links[4]['server_link']));
      }
    } catch (e) {}
  }
}
