// connector-projection-cutover records the explicit, fenced protocol boundary.
// Credentials are read only from CONNECTOR_CUTOVER_DSN, never command arguments.
package main

import (
	"context"
	"database/sql"
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"time"

	_ "github.com/go-sql-driver/mysql"
	controlplane "github.com/pingcap-inc/nexuscrm-controlplane"
)

func main() {
	packID := flag.String("pack-install-id", "", "exact installed connector incarnation")
	timeout := flag.Duration("timeout", 5*time.Minute, "bounded cutover deadline")
	flag.Parse()
	if err := run(*packID, *timeout); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func run(packID string, timeout time.Duration) error {
	dsn := os.Getenv("CONNECTOR_CUTOVER_DSN")
	if dsn == "" || packID == "" || timeout <= 0 {
		return fmt.Errorf("CONNECTOR_CUTOVER_DSN, -pack-install-id and a positive timeout are required")
	}
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return err
	}
	defer db.Close()
	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()
	result, err := controlplane.EnsureConnectorProjectionRangeProtocol(ctx, db, packID)
	if err != nil {
		return err
	}
	return json.NewEncoder(os.Stdout).Encode(result)
}
