package main

import (
	"bssapp-backend/db"
	"bssapp-backend/queries"
	"context"
	"flag"
	"fmt"
	"log"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/joho/godotenv"
)

func main() {
	mode := flag.String("mode", "delta", "refresh mode: full or delta")
	stage := flag.String("stage", "all", "start stage: sales, stock, price, kpi, all")
	startRaw := flag.String("start", "", "start date YYYY-MM-DD")
	endRaw := flag.String("end", "", "end date YYYY-MM-DD")
	prefix := flag.String("prefix", "", "optional product code prefix")
	mssqlTimeoutSec := flag.Int("mssql-timeout-sec", 0, "override MSSQL connection/dial timeout seconds")
	skipDelete := flag.Bool("skip-delete", false, "skip deleting existing cache rows")
	resumeAfter := flag.Int("resume-after", 0, "skip this many MSSQL rows before inserting")
	flag.Parse()

	_ = godotenv.Load(".env", "mail.env", ".env.local")

	if *mssqlTimeoutSec > 0 {
		timeout := strconv.Itoa(*mssqlTimeoutSec)
		_ = os.Setenv("MSSQL_CONNECTION_TIMEOUT_SEC", timeout)
		_ = os.Setenv("MSSQL_DIAL_TIMEOUT_SEC", timeout)
	}

	if err := db.ConnectMSSQL(); err != nil {
		log.Fatalf("mssql connect failed: %v", err)
	}
	pgDB, err := db.ConnectPostgres()
	if err != nil {
		log.Fatalf("postgres connect failed: %v", err)
	}
	defer pgDB.Close()

	startDate, err := parseDateFlag(*startRaw)
	if err != nil {
		log.Fatalf("invalid -start: %v", err)
	}
	endDate, err := parseDateFlag(*endRaw)
	if err != nil {
		log.Fatalf("invalid -end: %v", err)
	}

	ctx := context.Background()
	result, err := queries.RefreshProductPerformance(ctx, pgDB, queries.ProductPerformanceRefreshRequest{
		Mode:          strings.TrimSpace(*mode),
		Stage:         strings.TrimSpace(*stage),
		StartDate:     startDate,
		EndDate:       endDate,
		ProductPrefix: strings.TrimSpace(*prefix),
		SkipDelete:    *skipDelete,
		ResumeAfter:   *resumeAfter,
	})
	if err != nil {
		log.Fatalf("refresh failed: %v", err)
	}

	fmt.Printf("product performance refresh done: sales=%d stock=%d kpi=%d snapshots=%d\n",
		result.SalesRows,
		result.StockRows,
		result.KpiRows,
		result.SnapshotRows,
	)
}

func parseDateFlag(raw string) (time.Time, error) {
	raw = strings.TrimSpace(raw)
	if raw == "" {
		return time.Time{}, nil
	}
	return time.ParseInLocation("2006-01-02", raw, time.Local)
}
