package benefactorapp

import (
	"context"
	benefactorHttp "git.gocasts.ir/ebhomengo/niki/benefactorapp/delivery/http"
	repo "git.gocasts.ir/ebhomengo/niki/benefactorapp/repository/database"
	benefactor "git.gocasts.ir/ebhomengo/niki/benefactorapp/service"
	mySql "git.gocasts.ir/ebhomengo/niki/pkg/database/mysql"
	httpserver "git.gocasts.ir/ebhomengo/niki/pkg/httpserver"
	logger "git.gocasts.ir/ebhomengo/niki/pkg/logger"
)

type Application struct {
	Config            Config
	HTTPServer        benefactorHttp.Server
	BenefactorService benefactor.Service
	BenefactorHandler benefactorHttp.Handler
	BenefactorRepo    benefactor.Repository
	DBConn            mySql.DB
}

func Setup(ctx context.Context, config Config, DB mySql.DB) *Application {
	log := logger.L()
	log.Info("logger starting ...")

	db := mySql.New(config.MySQLDB)
	defer func() {
		if err := db.CloseStatements(); err != nil {
			log.Info("Error closing statements: %v\n", err)
		}
	}()
	log.Info("mysql connection starting ...")

	// Initialize repositories
	benefactorRepo := repo.New(db)
	benefactorValidator := benefactor.NewValidator(benefactorRepo)

	benefactorSvc := benefactor.NewService(benefactorRepo, benefactorValidator)
	benefactorHandler := benefactorHttp.NewHandler(benefactorSvc)

	hServer, hErr := httpserver.New(config.HTTPServer)
	if hErr != nil {
		log.Error("Http Server error: %v,\n", hErr)
	}
	httpServer := benefactorHttp.NewServer(*hServer, *benefactorHandler)

	return &Application{
		Config:            config,
		HTTPServer:        httpServer,
		BenefactorService: benefactorSvc,
		BenefactorHandler: *benefactorHandler,
		BenefactorRepo:    benefactorRepo,
		DBConn:            DB,
	}

}

func (app *Application) Start() {
	log := logger.L()
	log.Info("app starting ...")
	// TODO implementaion
}
