package main

import (
	"fmt"
	"log"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"golang.org/x/crypto/bcrypt"
)

type AppUser struct {
	Userid   int    `gorm:"primaryKey;column:userid"`
	Email    string `gorm:"column:email"`
	Password string `gorm:"column:password"`
	Roleid   int    `gorm:"column:roleid"`
	Authname string `gorm:"column:authname"`
}

func (AppUser) TableName() string {
	return "appusers"
}

func main() {
	dsn := "host=31.97.228.132 user=admin password=Package@321# dbname=logistics port=5433 sslmode=disable"
	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("failed to connect database: %v", err)
	}

	var users []AppUser
	result := db.Find(&users)
	if result.Error != nil {
		log.Fatalf("failed to query users: %v", result.Error)
	}

	if len(users) == 0 {
		fmt.Println("DATABASE IS EMPTY. No users found.")
		// Create default admin user
		hash, _ := bcrypt.GenerateFromPassword([]byte("admin123"), bcrypt.DefaultCost)
		
		admin := AppUser{
			Email:    "admin@doormile.com",
			Password: string(hash),
			Roleid:   1, // Admin
			Authname: "Super Admin",
		}
		if err := db.Create(&admin).Error; err != nil {
			log.Fatalf("Failed to create admin: %v", err)
		}
		fmt.Println("SUCCESS: Created default admin: admin@doormile.com / admin123")
	} else {
		fmt.Printf("Found %d users:\n", len(users))
		for _, u := range users {
			fmt.Printf("- %s (Email: %s, RoleID: %d)\n", u.Authname, u.Email, u.Roleid)
		}
	}
}
