//
// main.go
// Copyright (C) 2024 veypi <i@veypi.com>
// 2025-03-04 16:08:06
// Distributed under terms of the MIT license.
//

package main

import (
	"github.com/veypi/vbase"
	"github.com/veypi/vbase/cfg"
	"github.com/veypi/vbase/models"
	"github.com/veypi/vigo"
	"github.com/veypi/vigo/flags"
	"github.com/veypi/vigo/logv"
)

var cliOpts = &struct {
	Host string `json:"host"`
	Port int    `json:"port" short:"p"`
	*cfg.Options
}{
	Host:    "0.0.0.0",
	Port:    4000,
	Options: cfg.Config,
}

var (
	cmdMain = flags.New("app", "the backend server of app", cliOpts)
	cmdDB   = cmdMain.SubCommand("db", "database operations")
)

func init() {
	cmdMain.Command = runWeb
	cmdDB.SubCommand("migrate", "migrate database").Command = models.Migrate
	cmdDB.SubCommand("drop", "drop database").Command = models.Drop
	cmdDB.SubCommand("init", "init db data").Command = models.InitDB
}

func main() {
	cmdMain.Parse()
	err := cmdMain.Run()
	if err != nil {
		logv.Warn().Msg(err.Error())
	}
}

func runWeb() error {
	// 初始化权限系统
	if err := vbase.Auth.Init(); err != nil {
		return err
	}

	server, err := vigo.New(vigo.WithHost(cliOpts.Host), vigo.WithPort(cliOpts.Port))
	if err != nil {
		return err
	}
	server.SetRouter(vbase.Router)
	return server.Run()
}
