package main

import (
	"context"
	"fmt"
	"net"
	"os"
	"sipro-mps/internal/config"
	"sipro-mps/internal/marketplace"
	ozon "sipro-mps/internal/ozon/products"
	"sipro-mps/internal/redis"
	"sipro-mps/internal/tasks/client"
	wb "sipro-mps/internal/wb/products"
	ym "sipro-mps/internal/ym/products"

	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/joho/godotenv"
	"google.golang.org/grpc"
	_ "google.golang.org/grpc/encoding/gzip"
)

func logMessage(level string, format string, a ...interface{}) {
	const (
		green  = "\033[32m"
		red    = "\033[31m"
		yellow = "\033[33m"
		blue   = "\033[34m"
		reset  = "\033[0m"
	)
	switch level {
	case "info":
		fmt.Printf("%s✅ [INFO]%s %s %s\n", green, reset, fmt.Sprintf(format, a...), "ℹ️")
	case "error":
		fmt.Printf("%s❌ [ERROR]%s %s %s\n", red, reset, fmt.Sprintf(format, a...), "🚨")
	default:
		fmt.Printf("%s[LOG]%s %s\n", blue, reset, fmt.Sprintf(format, a...))
	}
}

func createGrpcServer(pool *pgxpool.Pool) {

	lis, err := net.Listen("tcp", ":8080")
	if err != nil {
		fmt.Printf("failed to listen: %v\n", err)
		return
	}
	grpcServer := grpc.NewServer()

	repo, err := marketplace.RegisterAdapterGRPC(grpcServer, pool)
	if err != nil {
		fmt.Printf("failed to register gRPC server: %v\n", err)
		return
	}
	_, err = ozon.RegisterAdapterGRPC(grpcServer, *repo)
	if err != nil {
		fmt.Printf("failed to register Ozon Products gRPC server: %v\n", err)
		return
	}
	_, err = wb.RegisterAdapterGRPC(grpcServer, *repo)
	if err != nil {
		fmt.Printf("failed to register Wildberries Products gRPC server: %v\n", err)
		return
	}

	_, err = ym.RegisterAdapterGRPC(grpcServer, *repo)
	if err != nil {
		fmt.Printf("failed to register Yandex Market Products gRPC server: %v\n", err)
		return

	}

	fmt.Println("gRPC server registered successfully.")
	// Start serving gRPC requests
	fmt.Println("gRPC server is starting on port 8080...")

	if err := grpcServer.Serve(lis); err != nil {
		fmt.Printf("failed to serve: %v\n", err)
	}
	fmt.Println("gRPC server created.")
}

func initDotenv() error {
	err := godotenv.Load()
	if err != nil {
		return fmt.Errorf("error loading .env file: %w", err)
	}
	logMessage("info", "Dotenv file loaded successfully. 🌱")
	return nil
}

func initRedisClient(ctx context.Context) error {
	err := redis.InitClient(ctx)
	if err != nil {
		return fmt.Errorf("error initializing Redis client: %w", err)
	}
	//defer redis.CloseClient()
	logMessage("info", "Redis client initialized successfully. 🟥")
	return nil
}
func initRedisLocker() error {
	err := redis.InitLocker()
	if err != nil {
		return fmt.Errorf("error initializing Redis locker: %w", err)
	}
	logMessage("info", "Redis locker initialized successfully. 🟥")
	return nil
}

func main() {
	err := initDotenv()
	if err != nil {
		logMessage("error", "Failed to load .env file: %v", err)
	}
	logMessage("info", "Starting the SIPRO Marketplace Server... 🚀1")
	ctx := context.Background()

	// Initializing the Redis client
	err = initRedisClient(ctx)
	if err != nil {
		logMessage("error", "Failed to initialize Redis client: %v", err)
		return
	}
	defer redis.CloseClient()

	// Initializing the Redis locker
	err = initRedisLocker()
	if err != nil {
		logMessage("error", "Failed to initialize Redis locker: %v", err)
		return
	}
	defer redis.CloseLocker()
	cfg, err := config.LoadConfig()
	if err != nil {
		logMessage("error", "Failed to load configuration: %v", err)
		return
	}

	client.InitClient(*cfg.Redis)
	// Initializing pgx connection
	dbpool, err := pgxpool.New(ctx, os.Getenv("POSTGRES_URL"))
	if err != nil {
		logMessage("error", "Failed to connect to PostgreSQL: %v", err)
		return
	}
	defer dbpool.Close()

	createGrpcServer(dbpool)
}
