import * as SQLite from 'expo-sqlite';

let db = null;

export async function openDb() {
  db = await SQLite.openDatabaseAsync('todos.db');
  return db;
}

export async function initDb() {
  if (!db) await openDb();
  await db.execAsync(`
    CREATE TABLE IF NOT EXISTS 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'))
    );
  `);
}

export async function getAllTodos() {
  if (!db) return [];
  const rows = await db.getAllAsync('SELECT * FROM todos ORDER BY created_at DESC');
  return rows.map(row => ({
    id: row.id,
    title: row.title,
    completed: row.completed === 1,
    category: row.category,
    priority: row.priority,
    createdAt: row.created_at,
  }));
}

export async function insertTodo(title, category, priority) {
  if (!db) return null;
  const result = await db.runAsync(
    'INSERT INTO todos (title, category, priority) VALUES (?, ?, ?)',
    [title, category, priority]
  );
  return result.lastInsertRowId;
}

export async function updateTodo(id, title, category, priority) {
  if (!db) return;
  await db.runAsync(
    'UPDATE todos SET title = ?, category = ?, priority = ? WHERE id = ?',
    [title, category, priority, id]
  );
}

export async function toggleTodo(id, completed) {
  if (!db) return;
  await db.runAsync(
    'UPDATE todos SET completed = ? WHERE id = ?',
    [completed ? 1 : 0, id]
  );
}

export async function deleteTodo(id) {
  if (!db) return;
  await db.runAsync('DELETE FROM todos WHERE id = ?', [id]);
}
