/*
 * Copyright (c) 2025-2026, Антон Аксенов
 * This file is part of iptvc project
 * MIT License: https://git.axenov.dev/IPTV/iptvc/src/branch/master/LICENSE
 */

package cache

import (
	"axenov/iptv-checker/app/config"
	"context"
	"fmt"
	"log"
	"strconv"

	"github.com/redis/go-redis/v9"
)

func Init(cfg *config.CacheConfig) *redis.Client {
	cacheAddr := fmt.Sprintf("%s:%s", cfg.Host, strconv.Itoa(int(cfg.Port)))
	cacheClient := redis.NewClient(&redis.Options{
		Addr:         cacheAddr,
		DB:           int(cfg.Db),
		PoolSize:     1000,
		ReadTimeout:  -1,
		WriteTimeout: -1,
	})
	client := cacheClient.Conn()
	ctx := context.Background()
	err := client.Ping(ctx).Err()
	if err == nil {
		log.Println("Connected to cache DB:", cacheAddr)
		cfg.IsActive = true
	} else {
		log.Println("Error while connecting to cache DB, program may work not as expected:", err)
	}

	return cacheClient
}
