1// SPDX-FileCopyrightText: Amolith <amolith@secluded.site>
2//
3// SPDX-License-Identifier: AGPL-3.0-or-later
4
5package person
6
7import (
8 "fmt"
9
10 "git.secluded.site/go-lunatask"
11 "git.secluded.site/lune/internal/client"
12 "git.secluded.site/lune/internal/completion"
13 "git.secluded.site/lune/internal/ui"
14 "git.secluded.site/lune/internal/validate"
15 "github.com/spf13/cobra"
16)
17
18// AddCmd creates a new person. Exported for potential use by shortcuts.
19var AddCmd = &cobra.Command{
20 Use: "add FIRST [LAST]",
21 Short: "Add a new person",
22 Long: `Add a new person to the Lunatask relationship tracker.
23
24First name is required; last name is optional.
25Use flags to set additional properties.`,
26 Args: cobra.RangeArgs(1, 2),
27 RunE: runAdd,
28}
29
30func init() {
31 AddCmd.Flags().StringP("relationship", "r", "", "Relationship strength")
32 AddCmd.Flags().String("source", "", "Source identifier")
33 AddCmd.Flags().String("source-id", "", "Source ID")
34
35 _ = AddCmd.RegisterFlagCompletionFunc("relationship", completion.Relationships)
36}
37
38func runAdd(cmd *cobra.Command, args []string) error {
39 firstName := args[0]
40
41 lastName := ""
42 if len(args) > 1 {
43 lastName = args[1]
44 }
45
46 apiClient, err := client.New()
47 if err != nil {
48 return err
49 }
50
51 builder := apiClient.NewPerson(firstName, lastName)
52
53 if err := applyRelationship(cmd, builder); err != nil {
54 return err
55 }
56
57 applySource(cmd, builder)
58
59 person, err := ui.Spin("Creating person…", func() (*lunatask.Person, error) {
60 return builder.Create(cmd.Context())
61 })
62 if err != nil {
63 return err
64 }
65
66 fmt.Fprintln(cmd.OutOrStdout(), ui.Success.Render("Created person: "+person.ID))
67
68 return nil
69}
70
71func applyRelationship(cmd *cobra.Command, builder *lunatask.PersonBuilder) error {
72 rel, _ := cmd.Flags().GetString("relationship")
73 if rel == "" {
74 return nil
75 }
76
77 strength, err := validate.RelationshipStrength(rel)
78 if err != nil {
79 return err
80 }
81
82 builder.WithRelationshipStrength(strength)
83
84 return nil
85}
86
87func applySource(cmd *cobra.Command, builder *lunatask.PersonBuilder) {
88 source, _ := cmd.Flags().GetString("source")
89 sourceID, _ := cmd.Flags().GetString("source-id")
90
91 if source != "" && sourceID != "" {
92 builder.FromSource(source, sourceID)
93 }
94}