import 'dart:async';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

import '../constant/app_constant.dart';

class DatabaseHelper {
  static Database? _database;

  Future<Database> get database async {
    _database ??= await _initDatabase();
    return _database!;
  }

  Future<Database> _initDatabase() async {
    String path = join(await getDatabasesPath(), AppConstant.dbName);

    return await openDatabase(
      path,
      version: 2,
      onCreate: _onCreate,
      onUpgrade: _onUpgrade,
    );
  }

  Future<void> _onCreate(Database db, int version) async {
    // Products table
    await db.execute('''
      CREATE TABLE products (
        id TEXT PRIMARY KEY,
        organization_id TEXT,
        category_id TEXT,
        sku TEXT,
        name TEXT,
        description TEXT,
        price INTEGER,
        cost INTEGER,
        business_type TEXT,
        image_url TEXT,
        printer_type TEXT,
        print_to_checker INTEGER DEFAULT 0,
        metadata TEXT,
        is_active INTEGER,
        created_at TEXT,
        updated_at TEXT
      )
    ''');

    // Product Variants table
    await db.execute('''
      CREATE TABLE product_variants (
        id TEXT PRIMARY KEY,
        product_id TEXT,
        name TEXT,
        price_modifier INTEGER,
        cost INTEGER,
        metadata TEXT,
        created_at TEXT,
        updated_at TEXT,
        FOREIGN KEY (product_id) REFERENCES products (id) ON DELETE CASCADE
      )
    ''');

    // Categories table - NEW
    await db.execute('''
      CREATE TABLE categories (
        id TEXT PRIMARY KEY,
        organization_id TEXT,
        name TEXT NOT NULL,
        description TEXT,
        business_type TEXT,
        sort_order INTEGER DEFAULT 0,
        metadata TEXT,
        is_active INTEGER DEFAULT 1,
        created_at TEXT,
        updated_at TEXT
      )
    ''');

    // Printer table
    await db.execute('''
      CREATE TABLE printers (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        code TEXT UNIQUE NOT NULL,
        name TEXT NOT NULL,
        address TEXT,
        paper TEXT,
        type TEXT,
        created_at TEXT,
        updated_at TEXT
      )
    ''');

    // Create indexes for better performance
    await db.execute(
      'CREATE INDEX idx_products_category_id ON products(category_id)',
    );
    await db.execute('CREATE INDEX idx_products_name ON products(name)');
    await db.execute('CREATE INDEX idx_products_sku ON products(sku)');
    await db.execute('CREATE INDEX idx_categories_name ON categories(name)');
    await db.execute(
      'CREATE INDEX idx_categories_organization_id ON categories(organization_id)',
    );
    await db.execute(
      'CREATE INDEX idx_categories_is_active ON categories(is_active)',
    );
    await db.execute('CREATE INDEX idx_printers_code ON printers(code)');
    await db.execute('CREATE INDEX idx_printers_type ON printers(type)');
  }

  Future<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
    if (oldVersion < 2) {
      await db.execute(
        'ALTER TABLE products ADD COLUMN print_to_checker INTEGER DEFAULT 0',
      );
    }
  }

  Future<void> close() async {
    final db = await database;
    await db.close();
    _database = null;
  }
}
