// Recipe "search": documents of one class modified in the last N days, newest first.
//
// Usage: go run ./recipes/search [class ID, default 1 "Other Document"] [days, default 30]
// [limit, default 10]
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/M-Files/mfiles-grpc-api-samples/mfilesclient"
	"github.com/M-Files/mfiles-grpc-api-samples/recipes/internal/recipe"
	"github.com/M-Files/mfiles-grpc-api/go/mfiles"
)

func main() {
	recipe.Main(run)
}

func run(ctx context.Context) error {
	classID := recipe.IntArg(0, 1)
	days := recipe.IntArg(1, 30)
	limit := recipe.IntArg(2, 10)
	client, err := recipe.Connect(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	// [START search]
	since := time.Now().UTC().AddDate(0, 0, -int(days))
	request := &mfiles.SearchObjectsRequest{
		// One array: all its conditions must match.
		Conditions: mfilesclient.AllOf(
			mfilesclient.IsObjectType(0), // documents
			mfilesclient.IsNotDeleted(),
			// Property 100 "Class" is a lookup into value list 1, the classes.
			mfilesclient.PropertyCondition(100, mfiles.ConditionType_CONDITION_TYPE_EQUAL,
				mfilesclient.Lookup(1, classID)),
			// Property 21 "Last modified" is a timestamp.
			mfilesclient.PropertyCondition(21,
				mfiles.ConditionType_CONDITION_TYPE_GREATER_THAN_OR_EQUAL,
				mfilesclient.Timestamp(since)),
		),
		// Newest first. The server sorts all matches, then returns the first `limit`.
		Sorting: mfilesclient.SortBy(21, true),
		Limit:   uint32(limit),
	}
	search := mfiles.NewIRPCSearchClient(client.Conn)
	response, err := search.SearchObjects(ctx, request)
	if err != nil {
		return err
	}
	// [END search]

	more := ""
	if response.GetHasMoreResults() {
		more = fmt.Sprintf(" (limited to %d; more exist)", limit)
	}
	fmt.Printf("Documents of class %d modified since %s: %d%s\n", classID,
		since.Format(time.DateOnly), len(response.GetResults()), more)
	for _, item := range response.GetResults() {
		fmt.Println("  " + recipe.Describe(item.GetObject()))
	}
	return nil
}
