// Package main is the entry point for the preferences-api service.
package main

import (
	"context"
	"flag"
	"fmt"
	"os"

	"git.threesix.ai/jordan/slack5-1770541397/pkg/app"
	"git.threesix.ai/jordan/slack5-1770541397/pkg/config"
	"git.threesix.ai/jordan/slack5-1770541397/pkg/database"
	"git.threesix.ai/jordan/slack5-1770541397/pkg/logging"
	"git.threesix.ai/jordan/slack5-1770541397/services/preferences-api/internal/adapter/postgres"
	"git.threesix.ai/jordan/slack5-1770541397/services/preferences-api/internal/api"
	"git.threesix.ai/jordan/slack5-1770541397/services/preferences-api/internal/service"
	"git.threesix.ai/jordan/slack5-1770541397/services/preferences-api/migrations"
)

func main() {
	// Parse flags
	exportOpenAPI := flag.Bool("export-openapi", false, "Export OpenAPI spec to stdout and exit")
	flag.Parse()

	// If exporting OpenAPI, generate spec and exit (used by CI for docs generation)
	if *exportOpenAPI {
		spec := api.NewServiceSpec()
		jsonBytes, err := spec.JSON()
		if err != nil {
			fmt.Fprintf(os.Stderr, "failed to generate OpenAPI spec: %v\n", err)
			os.Exit(1)
		}
		fmt.Println(string(jsonBytes))
		os.Exit(0)
	}

	// Create logger
	logger := logging.Default()

	// Connect to database
	dbCfg := config.ReadDatabaseConfig()
	pool, err := database.Connect(context.Background(), dbCfg.URL, database.Options{
		MaxOpenConns:    dbCfg.MaxOpenConns,
		MaxIdleConns:    dbCfg.MaxIdleConns,
		ConnMaxLifetime: dbCfg.ConnMaxLifetime,
	})
	if err != nil {
		logger.Error("failed to connect to database", "error", err)
		os.Exit(1)
	}

	// Run migrations
	database.MustRunMigrations(context.Background(), pool, migrations.FS, ".")

	// Create adapters (repositories)
	prefsRepo := postgres.NewPreferencesRepository(pool.DB, logger)

	// Create services (business logic)
	preferencesService := service.NewPreferencesService(prefsRepo, logger)

	// Create application
	application := app.New("preferences-api", app.WithDefaultPort(8001))

	// Register cleanup on shutdown
	application.OnShutdown(func(ctx context.Context) error {
		return pool.Close()
	})

	// Register routes with dependency injection
	api.RegisterRoutes(application, preferencesService)

	// Start server
	application.Run()
}
