package storage

import (
	"context"
	"fmt"
	"time"

	"git.warky.dev/wdevs/whatshooked/pkg/models"
	resolvespec_common "github.com/bitechdev/ResolveSpec/pkg/spectypes"
	"github.com/google/uuid"
	"golang.org/x/crypto/bcrypt"
)

// SeedData creates initial data for the application
func SeedData(ctx context.Context) error {
	if DB == nil {
		return fmt.Errorf("database not initialized")
	}

	// Check if admin user already exists
	userRepo := NewUserRepository(DB)
	_, err := userRepo.GetByUsername(ctx, "admin")
	if err == nil {
		// Admin user already exists
		return nil
	}

	// Create default admin user
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte("admin123"), bcrypt.DefaultCost)
	if err != nil {
		return fmt.Errorf("failed to hash password: %w", err)
	}

	now := time.Now()
	adminUser := &models.ModelPublicUsers{
		ID:        resolvespec_common.NewSqlString(uuid.New().String()),
		Username:  resolvespec_common.NewSqlString("admin"),
		Email:     resolvespec_common.NewSqlString("admin@whatshooked.local"),
		Password:  resolvespec_common.NewSqlString(string(hashedPassword)),
		FullName:  resolvespec_common.NewSqlString("System Administrator"),
		Role:      resolvespec_common.NewSqlString("admin"),
		Active:    true,
		CreatedAt: resolvespec_common.NewSqlTimeStamp(now),
		UpdatedAt: resolvespec_common.NewSqlTimeStamp(now),
	}

	if err := userRepo.Create(ctx, adminUser); err != nil {
		return fmt.Errorf("failed to create admin user: %w", err)
	}

	fmt.Println("✓ Created default admin user (username: admin, password: admin123)")
	fmt.Println("⚠ Please change the default password after first login!")

	return nil
}
