package dbstore

import (
	"git.linuxforward.com/byop/byop-engine/dbmanager"
	"git.linuxforward.com/byop/byop-engine/models"
	"github.com/google/uuid"
	"gorm.io/gorm"
)

// UserStore handles database operations for users
type UserStore struct {
	db *gorm.DB
}

// NewUserStore creates a new UserStore
func NewUserStore(dbManager dbmanager.DbManager) *UserStore {
	return &UserStore{
		db: dbManager.GetDB(),
	}
}

// Create creates a new user
func (us *UserStore) Create(user *models.User) error {
	// Generate ID if not provided
	if user.ID == "" {
		user.ID = uuid.New().String()
	}

	// GORM will handle created_at and updated_at automatically
	return us.db.Create(user).Error
}

// GetByID retrieves a user by ID
func (us *UserStore) GetByID(id string) (*models.User, error) {
	var user models.User
	result := us.db.First(&user, "id = ?", id)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return nil, nil // No user found
		}
		return nil, result.Error
	}
	return &user, nil
}

// GetByUsername retrieves a user by ID
func (us *UserStore) GetByUsername(id string) (*models.User, error) {
	var user models.User
	result := us.db.First(&user, "username = ?", id)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return nil, nil // No user found
		}
		return nil, result.Error
	}
	return &user, nil
}

// ListDeploymentsByUserID retrieves all deployments for a user by ID
func (us *UserStore) ListDeploymentsByUserID(userID string) ([]*models.Deployment, error) {
	var deployments []*models.Deployment
	result := us.db.Where("user_id = ?", userID).Find(&deployments)
	if result.Error != nil {
		return nil, result.Error
	}
	return deployments, nil
}

// Update updates an existing user
func (us *UserStore) Update(user *models.User) error {
	return us.db.Save(user).Error
}

// Delete deletes a user by ID
func (us *UserStore) Delete(id string) error {
	return us.db.Delete(&models.User{}, "id = ?", id).Error
}

// List retrieves all users with optional filtering
func (us *UserStore) List(filter map[string]interface{}) ([]*models.User, error) {
	var users []*models.User

	// Build query from filters
	query := us.db
	if filter != nil {
		for key, value := range filter {
			query = query.Where(key+" = ?", value)
		}
	}

	// Execute query
	if err := query.Find(&users).Error; err != nil {
		return nil, err
	}

	return users, nil
}

// GetUserByEmail retrieves a user by email
func (us *UserStore) GetUserByEmail(email string) (*models.User, error) {
	var user models.User
	result := us.db.Where("email = ?", email).First(&user)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return nil, nil // No user found
		}
		return nil, result.Error
	}
	return &user, nil
}
