package main

import (
	"context"
	"log"
	"os"
	"strconv"
	"time"

	"github.com/explorer/backend/api/rest"
	pgconfig "github.com/explorer/backend/libs/go-pgconfig"
	"github.com/jackc/pgx/v5/pgxpool"
)

func main() {
	ctx := context.Background()
	
	// Load database configuration (reusable lib: libs/go-pgconfig)
	dbConfig := pgconfig.LoadDatabaseConfig()
	poolConfig, err := dbConfig.PoolConfig()
	if err != nil {
		log.Fatalf("Failed to create pool config: %v", err)
	}

	// Connect to database
	db, err := pgxpool.NewWithConfig(ctx, poolConfig)
	if err != nil {
		log.Fatalf("Failed to connect to database: %v", err)
	}
	defer db.Close()

	// Configure connection pool
	db.Config().MaxConns = 25
	db.Config().MinConns = 5
	db.Config().MaxConnLifetime = 5 * time.Minute
	db.Config().MaxConnIdleTime = 10 * time.Minute

	chainID := 138
	if envChainID := os.Getenv("CHAIN_ID"); envChainID != "" {
		if id, err := strconv.Atoi(envChainID); err == nil {
			chainID = id
		}
	}

	port := 8080
	if envPort := os.Getenv("PORT"); envPort != "" {
		if p, err := strconv.Atoi(envPort); err == nil {
			port = p
		}
	}

	// Create and start server
	server := rest.NewServer(db, chainID)
	if err := server.Start(port); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}
