package main

import (
	"bssapp-backend/queries"
	"context"
	"database/sql"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

func startPricingParameterSyncScheduler(pgDB *sql.DB, mssqlDB *sql.DB) {
	enabled := strings.TrimSpace(strings.ToLower(os.Getenv("PRICING_PARAMETER_SYNC_ENABLED")))
	if enabled == "0" || enabled == "false" || enabled == "off" {
		log.Println("Pricing parameter sync scheduler disabled")
		return
	}

	intervalMin := 30
	if raw := strings.TrimSpace(os.Getenv("PRICING_PARAMETER_SYNC_INTERVAL_MIN")); raw != "" {
		if parsed, err := strconv.Atoi(raw); err == nil && parsed >= 5 {
			intervalMin = parsed
		}
	}

	runOnce := func(reason string) {
		if pgDB == nil || mssqlDB == nil {
			return
		}
		ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
		defer cancel()
		res, err := queries.SyncPricingParametersFromMSSQL(ctx, mssqlDB, pgDB)
		if err != nil {
			log.Printf("Pricing parameter sync failed (%s): %v", reason, err)
			return
		}
		log.Printf(
			"Pricing parameter sync ok (%s): total=%d upserted=%d deactivated=%d",
			reason,
			res.Total,
			res.Upserted,
			res.Deactivated,
		)
	}

	go func() {
		// Give the startup brand sync a short head start so brand_group_sec is
		// attached during the first parameter cache fill.
		time.Sleep(2 * time.Second)
		runOnce("startup")

		ticker := time.NewTicker(time.Duration(intervalMin) * time.Minute)
		defer ticker.Stop()
		for range ticker.C {
			runOnce("scheduled")
		}
	}()
}
