package cache

import (
	"encoding/json"
	"fmt"
	"log"
	"time"

	"gitea.local/admin/hspguard/internal/config"
	"github.com/redis/go-redis/v9"
	"golang.org/x/net/context"
)

type Client struct {
	rClient *redis.Client
}

func NewClient(cfg *config.AppConfig) *Client {
	opts, err := redis.ParseURL(cfg.RedisURL)
	if err != nil {
		log.Fatalln("ERR: Failed to get redis options:", err)
		return nil
	}

	client := redis.NewClient(opts)

	return &Client{
		rClient: client,
	}
}

type OAuthCode struct {
	ClientID string `json:"client_id"`
	UserID   string `json:"user_id"`
	Nonce    string `json:"nonce"`
}

type SaveAuthCodeParams struct {
	AuthCode string
	UserID   string
	ClientID string
	Nonce    string
}

func (c *Client) Set(ctx context.Context, key string, value any, expiration time.Duration) *redis.StatusCmd {
	return c.rClient.Set(ctx, key, value, expiration)
}

func (c *Client) SaveAuthCode(ctx context.Context, params *SaveAuthCodeParams) error {
	code := OAuthCode{
		ClientID: params.ClientID,
		UserID:   params.UserID,
		Nonce:    params.Nonce,
	}
	row, err := json.Marshal(&code)
	if err != nil {
		return err
	}

	return c.Set(ctx, fmt.Sprintf("oauth.%s", params.AuthCode), string(row), 5*time.Minute).Err()
}

func (c *Client) GetAuthCode(ctx context.Context, authCode string) (*OAuthCode, error) {
	row, err := c.Get(ctx, fmt.Sprintf("oauth.%s", authCode)).Result()
	if err != nil {
		return nil, err
	}

	if len(row) == 0 {
		return nil, fmt.Errorf("no auth params found under %s", authCode)
	}

	var parsed OAuthCode

	if err := json.Unmarshal([]byte(row), &parsed); err != nil {
		return nil, err
	}

	return &parsed, nil
}

func (c *Client) Get(ctx context.Context, key string) *redis.StringCmd {
	return c.rClient.Get(ctx, key)
}
