package main

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

	"github.com/StevanFreeborn/gator/internal/command"
	"github.com/StevanFreeborn/gator/internal/config"
	"github.com/StevanFreeborn/gator/internal/database"
	"github.com/StevanFreeborn/gator/internal/state"
	_ "github.com/lib/pq"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Not enough arguments provided. Usage: <command> <args>")
		os.Exit(1)
	}

	c, err := config.Read()

	if err != nil {
		fmt.Printf("Error reading config file: %s", err)
		os.Exit(1)
	}

	db, err := sql.Open("postgres", c.DbUrl)

	if err != nil {
		fmt.Printf("Error connecting to database: %s", err)
		os.Exit(1)
	}

	cmd := os.Args[1]
	args := os.Args[2:]

	dbQueries := database.New(db)
	s := state.NewState(dbQueries, c, args)

	registry := command.NewRegistry()
	err = registry.RunCommand(cmd, s)

	if err != nil {
		fmt.Printf("Error running '%s' command: %s\n", cmd, err)
		os.Exit(1)
	}

	os.Exit(0)
}
