package teller

import (
	"context"
	"crypto/tls"
	"encoding/json"
	"net/http"
	"time"

	"gogs.inhome.blapointe.com/ana-ledger/src/bank"
)

type Client struct {
	cert tls.Certificate
}

var _ bank.Agg = Client{}

func New() (Client, error) {
	cert, err := tls.LoadX509KeyPair("./certificate.pem", "./private_key.pem") // TODO
	return Client{cert: cert}, err
}

func (c Client) Accounts(ctx context.Context) ([]bank.Account, error) {
	var result []bank.Account
	err := c.get(ctx, "https://api.teller.io/accounts", &result)
	return result, err
}

func (c Client) Transactions(ctx context.Context, a bank.Account) ([]bank.Transaction, error) {
	var result []bank.Transaction
	err := c.get(ctx, "https://api.teller.io/accounts/"+a.Account+"/transactions", &result)
	return result, err
}

func (c Client) get(ctx context.Context, url string, ptr interface{}) error {
	httpc := &http.Client{
		Timeout: time.Second,
		Transport: &http.Transport{
			DisableKeepAlives: true,
			TLSClientConfig:   &tls.Config{Certificates: []tls.Certificate{c.cert}},
		},
	}

	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		return err
	}
	req.SetBasicAuth("test_token_bfu2cyvq3il6o", "") // TODO
	req = req.WithContext(ctx)

	resp, err := httpc.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	return json.NewDecoder(resp.Body).Decode(ptr)
}
