package pg

import (
	"context"
	"fmt"
	"github.com/go-pg/pg/v10"
	"github.com/go-pg/pg/v10/orm"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/constant"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/pg/models"
	_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/infrastructure/pg/models"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-cooperation/pkg/log"
	rawlog "log"
)

var DB *pg.DB

func init() {
	DB = pg.Connect(&pg.Options{
		User:     constant.POSTGRESQL_USER,
		Password: constant.POSTGRESQL_PASSWORD,
		Database: constant.POSTGRESQL_DB_NAME,
		Addr:     fmt.Sprintf("%s:%s", constant.POSTGRESQL_HOST, constant.POSTGRESQL_PORT),
	})
	if !constant.DISABLE_SQL_GENERATE_PRINT {
		DB.AddQueryHook(SqlGeneratePrintHook{})
	}
	if !constant.DISABLE_CREATE_TABLE {
		for _, model := range []interface{}{
			&models.ContractUndertakerFeedback{},
			&models.CooperationApplication{},
			&models.CooperationContract{},
			&models.CooperationContractChangeLog{},
			&models.CooperationContractRelevant{},
			&models.CooperationContractUndertaker{},
			&models.CooperationMode{},
			&models.CooperationProject{},
			&models.CreditAccount{},
			&models.DividendsEstimate{},
			&models.DividendsIncentivesRule{},
			&models.DividendsOrder{},
			&models.DividendsReturnedOrder{},
			&models.MoneyIncentivesRule{},
			&models.OrderGood{},
		} {
			err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
				Temp:          false,
				IfNotExists:   true,
				FKConstraints: true,
			})
			if err != nil {
				panic(err)
			}
			//comment.AddComments(DB, model)
		}
	}
}

type SqlGeneratePrintHook struct {
}

func (hook SqlGeneratePrintHook) BeforeQuery(c context.Context, q *pg.QueryEvent) (context.Context, error) {
	return c, nil
}

func (hook SqlGeneratePrintHook) AfterQuery(c context.Context, q *pg.QueryEvent) error {
	sqlStr, err := q.FormattedQuery()
	if err != nil {
		return err
	}
	if constant.LOG_FRAMEWORK == "logrus" {
		rawlog.Println(string(sqlStr))
	} else {
		log.Logger.Debug(string(sqlStr))
	}

	return nil
}