import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:slrpg_app/src/app.dart';
import 'package:slrpg_app/src/shared/data/local/app_database.dart';
import 'package:slrpg_app/src/shared/data/remote/api_client.dart';
import 'package:slrpg_app/src/shared/data/remote/pb_auth_store.dart';
import 'package:slrpg_app/src/core/utils/notification_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  try {
    await dotenv.load(fileName: '.env');
  } catch (e) {
    log('Could not load .env file: $e');
  }

  await SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown,
  ]);

  final notificationService = NotificationService();
  await notificationService.init();

  final database = AppDatabase();

  final authStore = PbAuthStore();
  await authStore.loadFromStorage();

  log("Auth loaded. Valid? ${authStore.isValid}");

  runApp(
    ProviderScope(
      overrides: [
        appDatabaseProvider.overrideWithValue(database),
        apiClientProvider
            .overrideWith((ref) => ApiClient(authStore: authStore)),
      ],
      child: const SLRPGApp(),
    ),
  );
}

final appDatabaseProvider =
    Provider<AppDatabase>((ref) => throw UnimplementedError());
