// Command migrate applies or reverts database schema migrations for the
// Pangolin server.
//
// Usage:
//
//	migrate up       – apply all pending migrations
//	migrate down     – revert all applied migrations
//	migrate version  – print the current migration version
//
// Configuration is read from the DB_DSN environment variable (a full MySQL
// DSN), consistent with the rest of the server.
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/wangjia/pangolin/server/internal/config"
	"github.com/wangjia/pangolin/server/internal/store"
)

func main() {
	if len(os.Args) < 2 {
		usage()
		os.Exit(1)
	}
	cmd := os.Args[1]

	driver := os.Getenv("DB_DRIVER")
	dsn := os.Getenv("DB_DSN")
	if dsn == "" {
		log.Fatal("migrate: DB_DSN is required")
	}

	db, err := store.Open(&config.Config{Driver: driver, DSN: dsn})
	if err != nil {
		log.Fatalf("migrate: db: %v", err)
	}
	defer db.Close()

	switch cmd {
	case "up":
		if err := store.MigrateUp(db, driver); err != nil {
			log.Fatalf("migrate up: %v", err)
		}
		log.Println("migrate: up — done")

	case "down":
		if err := store.MigrateDown(db, driver); err != nil {
			log.Fatalf("migrate down: %v", err)
		}
		log.Println("migrate: down — done")

	case "version":
		version, dirty, err := store.MigrateVersion(db, driver)
		if err != nil {
			log.Fatalf("migrate version: %v", err)
		}
		fmt.Printf("migrate: version=%d dirty=%v\n", version, dirty)

	default:
		fmt.Fprintf(os.Stderr, "migrate: unknown command %q\n", cmd)
		usage()
		os.Exit(1)
	}
}

func usage() {
	fmt.Fprintln(os.Stderr, "Usage: migrate <up|down|version>")
	fmt.Fprintln(os.Stderr, "")
	fmt.Fprintln(os.Stderr, "Environment variables:")
	fmt.Fprintln(os.Stderr, "  DB_DRIVER  mysql (default) | sqlite")
	fmt.Fprintln(os.Stderr, "  DB_DSN     mysql: full DSN · sqlite: file path or :memory: (required)")
}
