package run

import (
	"database/sql"
	"fmt"
	"github.com/jmoiron/sqlx"
	_ "modernc.org/sqlite"
)

var DB *sqlx.DB

func createTableIfNotExists(tableName string, schema string) error {
	var tmpName string
	sqCheck := "SELECT name FROM sqlite_master WHERE type='table' AND name=?"
	err := DB.QueryRow(sqCheck, tableName).Scan(&tmpName)

	if err != nil {
		if err != sql.ErrNoRows {
			return err
		}
	} else {
		return nil
	}

	_, err = DB.Exec(schema)
	return err
}

func InitDB(path string) error {
	var err error

	fname := fmt.Sprintf("%s/%s", path, "bordro_robot.db")

	DB, err = sqlx.Open("sqlite", fname)
	if err != nil {
		return err
	}

	companySchema := `
create table company (
	id INTEGER PRIMARY KEY AUTOINCREMENT,
	name text not null unique,
	member_number text not null,
	username text not null,
	password text not null
                     )
`
	err = createTableIfNotExists("company", companySchema)

	return err
}
