package docker

import (
	"context"
	"fmt"

	"github.com/moby/moby/client"
)

// Labels applied to all containers managed by docker-watcher.
const (
	LabelProject    = "docker-watcher.project"
	LabelStage      = "docker-watcher.stage"
	LabelInstanceID = "docker-watcher.instance-id"
)

// Client wraps the Docker Engine API client.
type Client struct {
	api client.APIClient
}

// New creates a new Docker client connected to the default Docker socket.
func New() (*Client, error) {
	api, err := client.NewClientWithOpts(
		client.FromEnv,
		client.WithAPIVersionNegotiation(),
	)
	if err != nil {
		return nil, fmt.Errorf("create docker client: %w", err)
	}

	return &Client{api: api}, nil
}

// Close releases resources held by the Docker client.
func (c *Client) Close() error {
	if err := c.api.Close(); err != nil {
		return fmt.Errorf("close docker client: %w", err)
	}
	return nil
}

// Ping checks connectivity to the Docker daemon.
func (c *Client) Ping(ctx context.Context) error {
	_, err := c.api.Ping(ctx, client.PingOptions{})
	if err != nil {
		return fmt.Errorf("ping docker daemon: %w", err)
	}
	return nil
}
