package main

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

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

	intervalMin := 30
	if raw := strings.TrimSpace(os.Getenv("BRAND_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(), 120*time.Second)
		defer cancel()
		res, err := queries.SyncBrandsFromMSSQL(ctx, mssqlDB, pgDB)
		if err != nil {
			log.Printf("❌ Brand sync failed (%s): %v", reason, err)
			return
		}
		log.Printf("✅ Brand sync ok (%s): total=%d upserted=%d deleted=%d", reason, res.Total, res.Upserted, res.Deleted)
	}

	go func() {
		runOnce("startup")

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