package main

import (
	"context"
	"embed"
	"flag"
	"fmt"

	"git.vdhsn.com/barretthousen/barretthousen/src/auth/internal"
	"git.vdhsn.com/barretthousen/barretthousen/src/auth/internal/data"
	"git.vdhsn.com/barretthousen/barretthousen/src/auth/internal/data/postgres"
	"git.vdhsn.com/barretthousen/barretthousen/src/auth/internal/domain"
	"git.vdhsn.com/barretthousen/barretthousen/src/lib/kernel"
	"github.com/jackc/pgx/v4/pgxpool"
	"go.uber.org/dig"
)

type (
	authApp struct {
		LogLevel   kernel.LogLevel           `yaml:"log_level" yaml-default:"0"`
		Port       int                       `yaml:"port" `
		DB_Service kernel.PostgresConnection `yaml:"db_service"`
		DB_Migrate kernel.PostgresConnection `yaml:"db_migrate"`
	}
)

var (
	migrate = flag.Bool("migrate", false, "migrates postgres db")
	client  = flag.String("client", "", "Runs this service in client mode, to invoke sync job. Takes GRPC endpoint")
	target  = flag.String("target", "", "To be used with client mode. The target to sync")

	//go:embed internal/data/postgres/migrations/*.sql
	dbMigrateScript embed.FS
)

func main() {
	flag.Parse()

	kernel.Run(context.Background(), &authApp{
		LogLevel: kernel.LevelTrace,
		Port:     5001,
	})
}

func (app *authApp) Start(ctx context.Context) error {
	if *migrate {
		if err := kernel.MigrateDB(ctx, app.DB_Migrate, dbMigrateScript, "auth"); err != nil {
			return fmt.Errorf("could not execute db migration: %w", err)
		}
	}

	ioc := dig.New()
	var err error
	if err = ioc.Provide(func() kernel.PostgresConnection {
		return app.DB_Service
	}); err != nil {
		return err
	}

	if err = ioc.Provide(func(pgCfg kernel.PostgresConnection) (*pgxpool.Pool, error) {
		return kernel.NewDBConnection(ctx, pgCfg)
	}); err != nil {
		return err
	}

	if err = ioc.Provide(func(pgConn *pgxpool.Pool) *postgres.Queries {
		return postgres.New(pgConn)
	}); err != nil {
		return err
	}

	if err = ioc.Provide(func(queries *postgres.Queries) domain.Storage {
		return &data.PGRunnerStorage{Queries: queries}
	}); err != nil {
		return err
	}

	if err = ioc.Provide(func(rs domain.Storage) *domain.Domain {
		return &domain.Domain{
			Storage: rs,
		}
	}); err != nil {
		return err
	}

	return ioc.Invoke(func(d *domain.Domain) error {
		authService := internal.NewAuthServer(d)

		if _, err := kernel.StartGRPCServer(ctx, app.Port, authService); err != nil {
			return err
		}

		return nil
	})
}

func (app *authApp) OnStop(ctx context.Context) {
}

func (app *authApp) GetLogLevel() kernel.LogLevel { return app.LogLevel }
