package main

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

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

type (
	catalogApp struct {
		LogLevel   kernel.LogLevel           `yaml:"log_level" env:"BH_LOG_LEVEL" env-default:"0" yaml-default:"0"`
		Port       int                       `yaml:"port" env:"catalog_PORT"`
		DB_Service kernel.PostgresConnection `yaml:"db_service" env:"catalog_DB_SERVICE"`
		DB_Migrate kernel.PostgresConnection `yaml:"db_migrate" env:"catalog_DB_MIGRATE"`
	}
)

var migrate = flag.Bool("migrate", false, "migrates postgres db")

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

func main() {
	flag.Parse()

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

func (app *catalogApp) Start(ctx context.Context) error {
	if *migrate {
		kernel.InfoLog.Printf("running db migrations on %v", app.DB_Migrate)
		if err := kernel.MigrateDB(ctx, app.DB_Migrate, dbMigrateScript, "catalog"); 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.PGCatalogStorage{Queries: queries}
	}); err != nil {
		return err
	}

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

	if err = ioc.Provide(func() (internal.KafkaConsumer, error) {
		return kafka.NewConsumer("runner.sync_results")
	}); err != nil {
		return err
	}

	return ioc.Invoke(func(d *domain.Usecase, consumer internal.KafkaConsumer) error {
		go internal.RunIndexer(ctx, consumer, d)

		catalogService := internal.NewCatalogServer(d)

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

		return nil
	})
}

func (app *catalogApp) OnStop(ctx context.Context) {
	if err := kernel.StopGRPCServer(); err != nil {
		kernel.ErrorLog.Printf("could not gracefully stop GRPC server: %v", err)
	}
}

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