/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 */
package maindb

import (
	"fmt"
	"path/filepath"

	"mstore/app/logger"

	"github.com/jmoiron/sqlx"
	_ "github.com/mattn/go-sqlite3"
)

type Database struct {
	datapath string
	logg     *logger.Logger
	db       *sqlx.DB
}

func NewDatabase(datapath string) *Database {
	return &Database{
		datapath: datapath,
		logg:     logger.NewLoggerWithSubject("maindb"),
	}
}

func (db *Database) OpenDatabase() error {
	var err error
	dbPath := filepath.Join(db.datapath, "mstore.db")
	db.db, err = sqlx.Open("sqlite3", fmt.Sprintf("%s?cache=shared&mode=rwc&_journal_mode=WAL", dbPath))
	if err != nil {
		return fmt.Errorf("Open database error: %v", err)
	}
	err = db.db.Ping()
	if err != nil {
		return fmt.Errorf("Ping database error: %v", err)
	}
	return err
}

func (db *Database) InitDatabase() error {
	var err error
	_, err = db.db.Exec(schema)
	if err != nil {
		return fmt.Errorf("Init database error: %v", err)
	}
	return err
}
