package main

import (
	"database/sql"

	_ "modernc.org/sqlite"
)

var db *sql.DB

const schema = `
CREATE TABLE IF NOT EXISTS user (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    uid        INTEGER UNIQUE,
    username   TEXT UNIQUE,
    password   BLOB,
    created_at INTEGER,
    last_login INTEGER
);

CREATE TABLE IF NOT EXISTS session (
    id          INTEGER PRIMARY KEY AUTOINCREMENT,
    uid         INTEGER,
    value       TEXT UNIQUE,
    created_at  INTEGER,
    expires     INTEGER,
    description TEXT
);

CREATE TABLE IF NOT EXISTS entry (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    pid        INTEGER UNIQUE,
    uid        INTEGER,
    created_at INTEGER,
    content    TEXT,
    filepath   TEXT
);

CREATE TABLE IF NOT EXISTS vote (
    id   INTEGER PRIMARY KEY AUTOINCREMENT,
    uid  INTEGER,
    pid  INTEGER,
    mode TEXT
);
`

func initDB() error {
	var err error
	db, err = sql.Open("sqlite", "kver.db")
	if err != nil {
		return err
	}
	if err = db.Ping(); err != nil {
		return err
	}
	_, err = db.Exec(schema)
	return err
}
