package main

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"log"
	"os"

	"github.com/joho/godotenv"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type ApiKey struct {
	ID               string `gorm:"primaryKey;type:uuid;default:gen_random_uuid()"`
	Name             string
	ClientID         string `gorm:"uniqueIndex"`
	ClientSecretHash string
	Scopes           string
	Status           string `gorm:"default:'active'"`
}

func generateToken(n int) string {
	b := make([]byte, n)
	if _, err := rand.Read(b); err != nil {
		panic(err)
	}
	return hex.EncodeToString(b)
}

func main() {
	godotenv.Load(".env")
	godotenv.Load("backend/.env")

	pgHost := os.Getenv("DB_HOST")
	if pgHost == "" {
		pgHost = "localhost"
	}
	pgPort := os.Getenv("DB_PORT")
	if pgPort == "" {
		pgPort = "5432"
	}
	pgUser := os.Getenv("DB_USER")
	if pgUser == "" {
		pgUser = "baron"
	}
	pgPass := os.Getenv("DB_PASSWORD")
	if pgPass == "" {
		pgPass = "password"
	}
	pgName := os.Getenv("DB_NAME")
	if pgName == "" {
		pgName = "baron_sso"
	}

	dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable",
		pgHost, pgUser, pgPass, pgName, pgPort)

	db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalf("Failed to connect to DB: %v", err)
	}

	clientID := generateToken(8)
	plainSecret := generateToken(16)
	hashedSecret, _ := bcrypt.GenerateFromPassword([]byte(plainSecret), bcrypt.DefaultCost)

	key := ApiKey{
		Name:             "Test Admin Key",
		ClientID:         clientID,
		ClientSecretHash: string(hashedSecret),
		Scopes:           "tenant:read tenant:write user:read user:write audit:read audit:write",
		Status:           "active",
	}

	if err := db.Table("api_keys").Create(&key).Error; err != nil {
		log.Fatalf("Failed to create API key: %v", err)
	}

	fmt.Println("====================================================")
	fmt.Println("✅ API Key Generated Successfully!")
	fmt.Printf("Client ID:     %s\n", clientID)
	fmt.Printf("Client Secret: %s\n", plainSecret)
	fmt.Println("====================================================")
	fmt.Println("Usage Example:")
	fmt.Printf("curl -H \"X-Baron-Key-ID: %s\" -H \"X-Baron-Key-Secret: %s\" http://localhost:3000/api/v1/admin/tenants\n", clientID, plainSecret)
	fmt.Println("====================================================")
}
