package accountapp

import (
	"log"

	"git.gocasts.ir/ebhomengo/niki/accountapp/delivery/grpc"
	"git.gocasts.ir/ebhomengo/niki/adapter/kavenegar"
	"git.gocasts.ir/ebhomengo/niki/adapter/redis"
	"git.gocasts.ir/ebhomengo/niki/domain/account/repository/mysql"
	redisRepo "git.gocasts.ir/ebhomengo/niki/domain/account/repository/redis"
	"git.gocasts.ir/ebhomengo/niki/domain/account/service"
	database "git.gocasts.ir/ebhomengo/niki/pkg/database/mysql"
	rpcPkg "git.gocasts.ir/ebhomengo/niki/pkg/grpc"
)

type Application struct {
	GrpcServer grpc.Server
	Config     Config
	accountSvc service.Service
}

func Setup(cfg Config, db *database.DB) Application {
	redisConn := redis.New(cfg.Redis)
	otpRepo := redisRepo.NewRepositoryOtp(redisConn)
	mysqlRepo := mysql.New(db)
	smsAdapter := kavenegar.New(cfg.Kavenegar)
	accountSvc := service.NewService(cfg.accountSvc, otpRepo, mysqlRepo, smsAdapter)

	rpcServer := rpcPkg.New(cfg.grpcServerCfg)

	return Application{
		accountSvc: accountSvc,
		Config:     cfg,
		GrpcServer: grpc.New(rpcServer, accountSvc),
	}
}

func (app *Application) Start() {
	err := app.GrpcServer.Start()
	if err != nil {
		log.Fatalf("error in serving GRPC server: %v", err)
	}

}
