package dbstore

import (
	"fmt"

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

// ClientStore handles database operations for clients
type ClientStore struct {
	db *gorm.DB
}

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

// Create creates a new client
func (cs *ClientStore) Create(client *models.Client) error {
	// Generate ID if not provided
	if client.ID == "" {
		client.ID = uuid.New().String()
	}

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

// GetByID retrieves a client by ID
func (cs *ClientStore) GetByID(id string) (*models.Client, error) {
	var client models.Client
	result := cs.db.First(&client, "id = ?", id)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return nil, nil // No client found
		}
		return nil, fmt.Errorf("failed to get client: %w", result.Error)
	}
	return &client, nil
}

// Update updates an existing client
func (cs *ClientStore) Update(client *models.Client) error {
	return cs.db.Save(client).Error
}

// Delete deletes a client by ID
func (cs *ClientStore) Delete(id string) error {
	return cs.db.Delete(&models.Client{}, "id = ?", id).Error
}

// List retrieves all clients with optional filtering
func (cs *ClientStore) List(filter map[string]interface{}) ([]*models.Client, error) {
	var clients []*models.Client

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

	// Execute query
	if err := query.Find(&clients).Error; err != nil {
		return nil, fmt.Errorf("failed to list clients: %w", err)
	}

	return clients, nil
}

// GetClientWithDeployments retrieves a client by ID with associated deployments
func (cs *ClientStore) GetClientWithDeployments(id string) (*models.Client, error) {
	var client models.Client
	result := cs.db.Preload("Deployments").First(&client, "id = ?", id)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return nil, nil // No client found
		}
		return nil, fmt.Errorf("failed to get client: %w", result.Error)
	}
	return &client, nil
}
