package main

import (
	"database/sql"
	"os"
	"os/signal"
	"sync"
	"syscall"

	_ "github.com/go-sql-driver/mysql"
	"github.com/marek/replica/pkg/replica"
)

func main() {
	// Initialize the logger
	replica.InitLogger()

	// Handle shutdown signals
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	// Connect to primary MariaDB
	primaryDSN := "root:replica@tcp(localhost:3306)/?multiStatements=true"
	primaryDB, err := sql.Open("mysql", primaryDSN)
	if err != nil {
		replica.Fatalf("Failed to connect to primary MariaDB: %v", err)
	}
	defer primaryDB.Close()

	primaryDB.SetMaxOpenConns(25)
	primaryDB.SetMaxIdleConns(5)

	if err := primaryDB.Ping(); err != nil {
		replica.Fatalf("Failed to ping primary MariaDB: %v", err)
	}
	replica.Info("Connected to primary MariaDB")

	// Connect to secondary MariaDB
	secondaryDSN := "root:replica@tcp(localhost:3307)/replica?multiStatements=true"
	secondaryDB, err := sql.Open("mysql", secondaryDSN)
	if err != nil {
		replica.Fatalf("Failed to connect to secondary MariaDB: %v", err)
	}
	defer secondaryDB.Close()

	secondaryDB.SetMaxOpenConns(25)
	secondaryDB.SetMaxIdleConns(5)

	if err := secondaryDB.Ping(); err != nil {
		replica.Fatalf("Failed to ping secondary MariaDB: %v", err)
	}
	replica.Info("Connected to secondary MariaDB")

	// MariaDB primary configuration
	primaryConfig := replica.BinlogConfig{
		Host:     "localhost",
		Port:     3306,
		User:     "root",
		Password: "replica",
		ServerID: 100,
		Name:     "mariadb-primary",
	}

	var wg sync.WaitGroup
	wg.Add(1)

	go func() {
		defer wg.Done()

		replica.Infof("Starting %s binlog sync...", primaryConfig.Name)

		// Create service with both primary and secondary connections
		service := replica.NewBinlogSyncService(primaryConfig, primaryDB, secondaryDB)

		// Use StartWithResync to automatically transfer data if needed
		// Parameters: batchSize=1000, excludeSchemas=["information_schema", "performance_schema", "mysql", "sys"]
		if err := service.StartWithResync(1000, []string{"information_schema", "performance_schema", "mysql", "sys"}); err != nil {
			replica.Errorf("Service error: %v", err)
		}
	}()

	sig := <-sigChan
	replica.Infof("Received %v, shutting down...", sig)

	wg.Wait()
	replica.Info("Service stopped.")
}
