package models

import (
	"context"
	"fmt"

	"git.paulbsd.com/paulbsd/ipbl/src/config"
	"xorm.io/xorm"
	"xorm.io/xorm/names"
)

var (
	x      *xorm.Engine
	tables []interface{}

	// HasEngine specifies if we have a xorm.Engine
	HasEngine bool
)

func init() {
	tables = append(tables,
		new(AutonomousSystem),
		new(Cfg),
		new(CfgSet),
		new(CfgTrustlist),
		new(CfgZMQ),
		new(City),
		new(Country),
		new(Event),
		new(IP),
		new(Src),
		new(Host),
	)
	for _, name := range []string{"SSL", "UID"} {
		names.LintGonicMapper[name] = true
	}
}

// NewEngine initializes a new xorm.Engine
func NewEngine(ctx *context.Context, config *config.Config) (err error) {
	var x = config.Db

	if err = x.Ping(); err != nil {
		return err
	}

	if err = x.Sync2(tables...); err != nil {
		return fmt.Errorf("sync database struct error: %v", err)
	}

	return nil
}

// DropTables initializes a new xorm.Engine
func DropTables(ctx *context.Context, config *config.Config) (err error) {
	var x = config.Db

	if err = x.Ping(); err != nil {
		return err
	}

	if err = x.Sync2(tables...); err != nil {
		return fmt.Errorf("sync database struct error: %v", err)
	}

	return nil
}
