import 'dart:io' show Platform, Directory;
import 'package:path/path.dart' as path;
import 'package:sqflite_common_ffi/sqflite_ffi.dart';

const settingsDir = '.gamer-updater';
const dbFileName = 'data.db';

class DB {
  static late Database db;

  // SQL schema definition
  static const String _schema = '''
CREATE TABLE IF NOT EXISTS games (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT NOT NULL,
  actual_version TEXT NOT NULL,
  last_played TEXT NOT NULL,
  rss_feed_url TEXT NOT NULL,
  version_regex TEXT NOT NULL,
  last_updated TEXT NOT NULL,
  image_data BLOB
);
CREATE INDEX IF NOT EXISTS idx_games_name ON games (name);
CREATE UNIQUE INDEX IF NOT EXISTS idx_games_name_unique ON games (name);
''';

  static Future<String> _getDatabasePath() async {
    print('Attempting to get database path...');
    if (Platform.isWindows || Platform.isLinux) {
      // Get user's home directory
      final home =
          Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'];
      if (home == null) {
        throw Exception('Could not find home directory');
      }
      print('Home directory found: home');

      final dbDir = Directory(path.join(home, settingsDir));
      if (!await dbDir.exists()) {
        await dbDir.create(recursive: true);
        print('$settingsDir directory created');
      } else {
        print('$settingsDir directory already exists');
      }

      return path.join(dbDir.path, dbFileName);
    } else {
      // Default path for other platforms
      final databasesPath = await databaseFactoryFfi.getDatabasesPath();
      print('Using default databases path: databasesPath');
      return path.join(databasesPath, dbFileName);
    }
  }

  static Future<void> init() async {
    print('Starting database initialization...');
    sqfliteFfiInit();

    final dbPath = await _getDatabasePath();
    print('Database path: dbPath');

    try {
      db = await databaseFactoryFfi.openDatabase(
        dbPath,
        options: OpenDatabaseOptions(
          version: 1,
          onCreate: (db, version) async {
            print('Creating database schema...');
            await db.execute(_schema);
            print('Database schema created successfully');
          },
        ),
      );
      print('Database opened and initialized');
    } catch (e) {
      print('Failed to initialize database: e');
      rethrow;
    }
  }
}
