import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';
import type { Settings } from '../models/settings';

const sqlite = new SQLiteConnection(CapacitorSQLite);

export async function initDB() {
  const db = await sqlite.createConnection('membersDB', true, 'secreto_passwordo', 1, false);
  await db.open();
  await db.execute(`CREATE TABLE IF NOT EXISTS users (
						id INTEGER PRIMARY KEY AUTOINCREMENT,
						username TEXT NOT NULL,
						role TEXT NOT NULL,
						password TEXT NOT NULL,
						settings TEXT NOT NULL
						);`);

  const result = await db.query(`SELECT * FROM users WHERE username = ?`, ['admin']);
  if (result.values?.length === 0) {
    await db.run(`INSERT INTO users (username, role, password, settings) VALUES (?, ?, ?, ?)`, [
      'admin',
      'admin',
      'tecamino@2023',
      {},
    ]);
  }
  return db;
}

export async function addUser(user: string, role: string, password: string, settings: Settings) {
  const db = await initDB();
  await db.run(`INSERT INTO users (username, role, password, settings) VALUES (?, ?, ?, ?)`, [
    user,
    role,
    password,
    settings,
  ]);
}

export async function getUsers() {
  const db = await initDB();
  const resp = await db.query(`SELECT * FROM users`);
  return resp.values;
}

export async function getUser(user: string) {
  const db = await initDB();
  const resp = await db.query(`SELECT EXISTS(SELECT 1 FROM users WHERE username = ?)`, [user]);
  return resp.values;
}
