import Database from 'bun:sqlite';
import { dev } from '$app/environment';

// Initialize the database
const db = new Database('sludge.db', { create: true });

db.exec(`
  CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT UNIQUE NOT NULL,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  );
`);

db.exec(`
  CREATE TABLE IF NOT EXISTS
  'pork_cuts' (
    'id' integer not null primary key autoincrement,
    'name' varchar(40) null,
    'raw_cut' BOOLEAN null,
    'stock' INT null default 0,
    "preweighed" BOOLEAN NULL,
    "min_weight" DOUBLE NULL,
    "max_weight" DOUBLE NULL,
    unique ('id')
  )
`);

db.exec(`
  CREATE TABLE IF NOT EXISTS
  'fest_count' (
    'year' integer not null primary key,
    'people' integer not null default 0,
    'cars' integer not null default 0,
    'tents' integer not null default 0
  )`);

db.exec('INSERT OR IGNORE INTO fest_count(year) VALUES (25)');

// Close the database connection when the application shuts down
process.on('SIGINT', () => {
  db.close(false);
  process.exit(0);
});

// Export database instance and helper functions
export { db };

export function get_all_blags() {
  return db.query('SELECT * FROM blags').all();
}

export function get_blag(uri) {
  return db.query('SELECT * FROM blags WHERE uri = ?').get(uri);
}


export function create_user(name: string, email: string) {
  try {
    const result = db.query('INSERT INTO users (name, email) VALUES ($name, $email)').get({ $name: name, $email: email });
    return { success: true, id: result.lastInsertRowid, name, email };
  } catch (error) {
    console.error(error);
    return { success: false, error: 'Failed to create user' + (error as Error).message };
  }
}

export function get_user(name: string) {
  return db.query('SELECT * FROM users WHERE name = ?').get(name);
}

export function get_all_pork() {
  return db.query('SELECT * FROM pork_cuts').all();
}


export function publish_blog(title, uri, body) {
  db.query('INSERT INTO blags (title, uri, body) VALUES ($title, $uri, $body)').get({ $title: title, $uri: uri, $body: body });
  return { success: true, uri }
}


/**
 * Clicker Stuff
 *
 *
 */

export function get_fest_counts(year = 25) {
  return db.query('SELECT * FROM fest_count WHERE year = ?').get(year)
}

export function add_fest_counts(people, tents, cars, year) {
  console.log('asc', { people, tents, cars, year })
  db.query('UPDATE fest_count SET people = ?, tents = ?, cars = ? WHERE year = ?').get(people, tents, cars, year)
  return true
}
/**
 * Thread Stuff
 * 
 * 
 * 
 */

export function get_all_threads() {
  return db.query('SELECT * FROM threads').all();
}


export function create_thread(title, id, creator) {

  db.query('INSERT INTO threads (id, title, progenator) VALUES ($id, $title, $creator)').get({ $id: id, $title: title, $creator: creator })

  return db.query(`CREATE TABLE
  '${id}' (
    'id' integer not null primary key autoincrement,
    'created_at' datetime not null default CURRENT_TIMESTAMP,
    'author' INT not null,
    "is_edited?" BOOLEAN not null,
    'content' TEXT not null,
    unique ('id'),
    foreign key('author') references users('id')
  )`)
}
