package main

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/joho/godotenv"
	_ "github.com/lib/pq"
)

func main() {
	pwd, _ := os.Getwd()
	log.Printf("Current Working Directory: %s", pwd)

	if err := godotenv.Load(".env"); err != nil {
		// Try loading from parent if not in root
		if err := godotenv.Load("../.env"); err != nil {
			log.Println("No .env file found")
		}
	}

	dbURL := os.Getenv("DATABASE_URL")
	if dbURL == "" {
		host := os.Getenv("DB_HOST")
		port := os.Getenv("DB_PORT")
		user := os.Getenv("DB_USER")
		pass := os.Getenv("DB_PASSWORD")
		name := os.Getenv("DB_NAME")
		ssl := os.Getenv("DB_SSLMODE")
		if host != "" {
			dbURL = fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=%s", user, pass, host, port, name, ssl)
		} else {
			// Last resort
			dbURL = "postgres://postgres:postgres@localhost:5432/gohorsejobs?sslmode=disable"
		}
	}

	db, err := sql.Open("postgres", dbURL)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Try multiple paths
	paths := []string{
		"migrations/017_create_tickets_table.sql",
		"backend/migrations/017_create_tickets_table.sql",
		"../migrations/017_create_tickets_table.sql",
		"/home/yamamoto/lab/gohorsejobs/backend/migrations/017_create_tickets_table.sql",
	}

	var content []byte
	var readErr error

	for _, p := range paths {
		content, readErr = os.ReadFile(p)
		if readErr == nil {
			log.Printf("Found migration at: %s", p)
			break
		}
	}

	if content == nil {
		log.Fatalf("Could not find migration file. Last error: %v", readErr)
	}

	statements := strings.Split(string(content), ";")
	for _, stmt := range statements {
		trimmed := strings.TrimSpace(stmt)
		if trimmed == "" {
			continue
		}
		log.Printf("Executing: %s", trimmed)
		_, err = db.Exec(trimmed)
		if err != nil {
			// Log but maybe don't fail if it's just "already exists"?
			// But we want to be strict.
			// If it's "relation already exists", we might ignore.
			if strings.Contains(err.Error(), "already exists") {
				log.Printf("Warning (ignored): %v", err)
			} else {
				log.Printf("FAILED executing: %s\nError: %v", trimmed, err)
				// Fail?
				// log.Fatal(err)
			}
		}
	}

	fmt.Println("Migration 017 applied successfully")
}
