package main

import (
	"fmt"
	"log"
	"os"

	"stock-user-system/internal/config"
	"stock-user-system/internal/db"
	"stock-user-system/internal/models"
	"stock-user-system/internal/routes"
)

func main() {
	cfg, err := config.Load()
	if err != nil {
		log.Fatalf("load config: %v", err)
	}

	database, err := db.Init(cfg.DatabaseURL)
	if err != nil {
		log.Fatalf("init database: %v", err)
	}

	if err := models.AutoMigrate(database); err != nil {
		log.Fatalf("migrate database: %v", err)
	}

	if err := models.SeedRoles(database); err != nil {
		log.Fatalf("seed roles: %v", err)
	}

	if err := models.SeedSystemAdmin(database); err != nil {
		log.Fatalf("seed system admin: %v", err)
	}

	r := routes.Setup(cfg, database)

	addr := fmt.Sprintf("0.0.0.0:%s", cfg.Port)
	log.Printf("backend listening on %s", addr)

	if err := r.Run(addr); err != nil {
		log.Fatalf("server error: %v", err)
		os.Exit(1)
	}
}
