package dbstore

import (
	"fmt"

	"git.linuxforward.com/byop/byop-engine/dbmanager"
	"git.linuxforward.com/byop/byop-engine/models"
)

type ClientStore struct {
	dbConn dbmanager.DbManager
}

// NewClientStore creates a new ClientStore
func NewClientStore(dbConn dbmanager.DbManager) *ClientStore {
	return &ClientStore{
		dbConn: dbConn,
	}
}
func (cs *ClientStore) CreateTable() error {
	query := `
    CREATE TABLE IF NOT EXISTS clients (
        id TEXT PRIMARY KEY,
        data TEXT NOT NULL
    );`
	_, err := cs.dbConn.Exec(query)
	if err != nil {
		return fmt.Errorf("failed to create clients table: %w", err)
	}
	return nil
}

// Create creates a new user
func (us *ClientStore) Create(user *models.Client) error {
	return us.dbConn.Create("clients", user)
}

// GetByID retrieves a user by ID
func (us *ClientStore) GetByID(id string) (*models.Client, error) {
	user, err := us.dbConn.GetByID("clients", id)
	if err != nil {
		return nil, err
	}
	return user.(*models.Client), nil
}

// Update updates an existing user
func (us *ClientStore) Update(user *models.Client) error {
	return us.dbConn.Update("clients", user)
}

// Delete deletes a user by ID
func (us *ClientStore) Delete(id string) error {
	return us.dbConn.Delete("clients", id)
}

// List retrieves all clients
func (us *ClientStore) List(filter map[string]interface{}) ([]*models.Client, error) {
	clients, err := us.dbConn.List("clients", filter)
	if err != nil {
		return nil, err
	}

	var userList []*models.Client
	for _, user := range clients {
		userList = append(userList, user.(*models.Client))
	}
	return userList, nil
}
