import * as SQLite from 'expo-sqlite';

let db: SQLite.SQLiteDatabase | null = null;

export const getDBConnection = async (): Promise<SQLite.SQLiteDatabase> => {
  if (db) return db;
  db = await SQLite.openDatabaseAsync('geosport_log.db');
  
  // Khởi tạo các bảng dữ liệu nếu chưa tồn tại
  await db.execAsync(`
    PRAGMA foreign_keys = ON;

    CREATE TABLE IF NOT EXISTS workouts (
      id TEXT PRIMARY KEY NOT NULL,
      title TEXT NOT NULL,
      type TEXT NOT NULL, /* RUNNING, CYCLING, WALKING */
      date TEXT NOT NULL, /* YYYY-MM-DD */
      start_time INTEGER NOT NULL, /* Timestamp */
      duration INTEGER NOT NULL, /* Seconds */
      distance REAL NOT NULL, /* Km */
      avg_speed REAL NOT NULL,
      avg_hr INTEGER,
      calories INTEGER NOT NULL
    );

    CREATE TABLE IF NOT EXISTS trackpoints (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      workout_id TEXT NOT NULL,
      latitude REAL NOT NULL,
      longitude REAL NOT NULL,
      speed REAL NOT NULL,
      heart_rate INTEGER,
      timestamp INTEGER NOT NULL,
      FOREIGN KEY (workout_id) REFERENCES workouts (id) ON DELETE CASCADE
    );

    CREATE TABLE IF NOT EXISTS media_attachments (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      workout_id TEXT NOT NULL,
      latitude REAL NOT NULL,
      longitude REAL NOT NULL,
      type TEXT NOT NULL, /* IMAGE, VIDEO */
      file_uri TEXT NOT NULL, /* Local File System URI */
      caption TEXT,
      timestamp INTEGER NOT NULL,
      FOREIGN KEY (workout_id) REFERENCES workouts (id) ON DELETE CASCADE
    );
  `);
  
  return db;
};
