/*
  * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 *
 *
*/

package repocli

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"time"
)

type JWT struct {
	Token       string    `json:"token"`
	AccessToken string    `json:"access_token"`
	ExpiresIn   int       `json:"expires_in"`
	IssuedAt    time.Time `json:"issued_at"`
}

func (cli *Client) GetToken(ctx context.Context, uri string) (string, error) {
	var err error
	var token string

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
	if err != nil {
		return token, err
	}
	req.Header.Set("User-Agent", cli.userAgent)
	req.Header.Set("Accept", "*/*")
	resp, err := cli.httpClient.Do(req)
	if err != nil {
		return token, err
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusNotFound {
		return token, err
	}
	if resp.StatusCode != http.StatusOK {
		err := fmt.Errorf("Unxected response code %s", resp.Status)
		return token, err
	}
	mime := resp.Header.Get("Content-Type")
	if mime != "application/json" {
		err := fmt.Errorf("Empty MIME type declaration")
		return token, err
	}
	buffer := bytes.NewBuffer(nil)
	recSize, err := Copy(ctx, buffer, resp.Body)
	if recSize == 0 {
		err := fmt.Errorf("Zero actual body size")
		return token, err
	}
	tokenJson := buffer.Bytes()
	jwt := &JWT{}
	err = json.Unmarshal(tokenJson, jwt)
	if err != nil {
		return token, err
	}
	token = jwt.Token
	return token, err
}
