package dbstore

import (
	"context"
	"fmt"

	"git.linuxforward.com/byop/byop-engine/models"
	"gorm.io/gorm"
)

// CreateClient creates a new client using GORM
func (s *SQLiteStore) CreateClient(ctx context.Context, client *models.Client) error {
	result := s.db.WithContext(ctx).Create(client)
	if result.Error != nil {
		return fmt.Errorf("failed to create client: %w", result.Error)
	}
	return nil
}

// GetAllClients retrieves all clients using GORM
func (s *SQLiteStore) GetAllClients(ctx context.Context) ([]*models.Client, error) {
	var clients []*models.Client
	result := s.db.WithContext(ctx).Find(&clients)
	if result.Error != nil {
		return nil, fmt.Errorf("failed to get all clients: %w", result.Error)
	}
	return clients, nil
}

// GetClientByID retrieves a client by ID using GORM
func (s *SQLiteStore) GetClientByID(ctx context.Context, id uint) (*models.Client, error) {
	var client models.Client
	result := s.db.WithContext(ctx).First(&client, id)
	if result.Error != nil {
		if result.Error == gorm.ErrRecordNotFound {
			return nil, models.NewErrNotFound(fmt.Sprintf("client with ID %d not found", id), result.Error)
		}
		return nil, fmt.Errorf("failed to get client by ID: %w", result.Error)
	}
	return &client, nil
}

// UpdateClient updates an existing client using GORM
func (s *SQLiteStore) UpdateClient(ctx context.Context, client *models.Client) error {
	result := s.db.WithContext(ctx).Save(client)
	if result.Error != nil {
		return fmt.Errorf("failed to update client: %w", result.Error)
	}
	if result.RowsAffected == 0 {
		return models.NewErrNotFound(fmt.Sprintf("client with ID %d not found for update", client.ID), nil)
	}
	return nil
}

// DeleteClient deletes a client by ID using GORM
func (s *SQLiteStore) DeleteClient(ctx context.Context, id uint) error {
	result := s.db.WithContext(ctx).Delete(&models.Client{}, id)
	if result.Error != nil {
		return fmt.Errorf("failed to delete client: %w", result.Error)
	}
	if result.RowsAffected == 0 {
		return models.NewErrNotFound(fmt.Sprintf("client with ID %d not found for deletion", id), nil)
	}
	return nil
}
