package client

import (
	"context"
	"fmt"
	"io"
	"net/url"
	"sync"
	"time"

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

// ServiceLogsOptions holds parameters to filter logs with.
type ServiceLogsOptions struct {
	ShowStdout bool
	ShowStderr bool
	Since      string
	Until      string
	Timestamps bool
	Follow     bool
	Tail       string
	Details    bool
}

// ServiceLogsResult holds the result of a service logs operation.
// It implements [io.ReadCloser].
// It's up to the caller to close the stream.
type ServiceLogsResult struct {
	rc    io.ReadCloser
	close func() error
}

// ServiceLogs returns the logs generated by a service in an [ServiceLogsResult].
func (cli *Client) ServiceLogs(ctx context.Context, serviceID string, options ServiceLogsOptions) (ServiceLogsResult, error) {
	serviceID, err := trimID("service", serviceID)
	if err != nil {
		return ServiceLogsResult{}, err
	}

	query := url.Values{}
	if options.ShowStdout {
		query.Set("stdout", "1")
	}

	if options.ShowStderr {
		query.Set("stderr", "1")
	}

	if options.Since != "" {
		ts, err := timestamp.GetTimestamp(options.Since, time.Now())
		if err != nil {
			return ServiceLogsResult{}, fmt.Errorf(`invalid value for "since": %w`, err)
		}
		query.Set("since", ts)
	}

	if options.Timestamps {
		query.Set("timestamps", "1")
	}

	if options.Details {
		query.Set("details", "1")
	}

	if options.Follow {
		query.Set("follow", "1")
	}
	query.Set("tail", options.Tail)

	resp, err := cli.get(ctx, "/services/"+serviceID+"/logs", query, nil)
	if err != nil {
		return ServiceLogsResult{}, err
	}
	return newServiceLogsResult(resp.Body), nil
}

func newServiceLogsResult(rc io.ReadCloser) ServiceLogsResult {
	if rc == nil {
		panic("nil io.ReadCloser")
	}
	return ServiceLogsResult{
		rc:    rc,
		close: sync.OnceValue(rc.Close),
	}
}

// Read implements [io.ReadCloser] for LogsResult.
func (r ServiceLogsResult) Read(p []byte) (n int, err error) {
	if r.rc == nil {
		return 0, io.EOF
	}
	return r.rc.Read(p)
}

// Close implements [io.ReadCloser] for LogsResult.
func (r ServiceLogsResult) Close() error {
	if r.close == nil {
		return nil
	}
	return r.close()
}
