import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'models/todo.dart';

class TodoDatabase {
  static Database? _db;

  static Future<void> init() async {
    final dir = await getApplicationDocumentsDirectory();
    final dbPath = p.join(dir.path, 'todos.db');
    _db = await openDatabase(
      dbPath,
      version: 1,
      onCreate: (db, version) async {
        await db.execute('''
          CREATE TABLE todos (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            title TEXT NOT NULL,
            completed INTEGER DEFAULT 0,
            category TEXT DEFAULT 'Personal',
            priority TEXT DEFAULT 'medium',
            created_at INTEGER DEFAULT (strftime('%s','now'))
          )
        ''');
      },
    );
  }

  static Future<List<Todo>> loadTodos() async {
    if (_db == null) return [];
    final rows = await _db!.query('todos', orderBy: 'created_at DESC');
    return rows.map((row) => Todo.fromMap(row)).toList();
  }

  static Future<int> insertTodo(String title, String category, String priority) async {
    if (_db == null) return -1;
    return await _db!.insert('todos', {
      'title': title,
      'category': category,
      'priority': priority,
      'completed': 0,
    });
  }

  static Future<void> updateTodo(int id, String title, String category, String priority) async {
    if (_db == null) return;
    await _db!.update(
      'todos',
      {'title': title, 'category': category, 'priority': priority},
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  static Future<void> toggleTodo(int id, bool completed) async {
    if (_db == null) return;
    await _db!.update(
      'todos',
      {'completed': completed ? 1 : 0},
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  static Future<void> deleteTodo(int id) async {
    if (_db == null) return;
    await _db!.delete('todos', where: 'id = ?', whereArgs: [id]);
  }
}
