package main

import (
	"encoding/json"
	"fmt"
)

func cmdAccounts(args []string) error {
	if len(args) == 0 {
		return fmt.Errorf("accounts: expected 'list' or 'get'")
	}
	c, err := NewClient()
	if err != nil {
		return err
	}
	switch args[0] {
	case "list", "ls":
		return cmdAccountsList(c, args[1:])
	case "get":
		return cmdAccountsGet(c, args[1:])
	default:
		return fmt.Errorf("accounts: unknown verb %q (want: list, get)", args[0])
	}
}

func cmdAccountsList(c *Client, args []string) error {
	o, _, err := parseListFlags("accounts list", args)
	if err != nil {
		return err
	}
	items, p, raw, err := c.fetchList("/accounts", o)
	if err != nil {
		return err
	}
	return emitList(items, p, raw, o, func(items []json.RawMessage) error {
		tw := newTab()
		fmt.Fprintln(tw, "ID\tNAME")
		for _, rm := range items {
			var a Account
			_ = json.Unmarshal(rm, &a)
			fmt.Fprintf(tw, "%s\t%s\n", a.ID, a.Name)
		}
		return tw.Flush()
	})
}

func cmdAccountsGet(c *Client, args []string) error {
	jsonMode, id, err := parseGetFlags("accounts get", args)
	if err != nil {
		return err
	}
	var a Account
	var raw []byte
	if err := c.get(apiPrefix+"/accounts/"+pathID(id), &a, &raw); err != nil {
		return err
	}
	if jsonMode {
		return printJSON(raw)
	}
	tw := newTab()
	fmt.Fprintln(tw, "ID\tNAME")
	fmt.Fprintf(tw, "%s\t%s\n", a.ID, a.Name)
	return tw.Flush()
}
