package dto

import (
	"dataservices/commons/utils"
	"time"

	"google.golang.org/protobuf/types/known/timestamppb"
)

// @Time    : 2022/12/13 2:32 PM
// @Author  : lvhongmeng

type APIKeys struct {
	ID        uint64         `json:"id"`
	DataAppId uint64         `json:"dataapp_id"`
	Name      string         `json:"name"`
	CreatedBy string         `json:"created_by"`
	IsDeleted int8           `json:"is_deleted"`
	CreatedAt utils.JsonTime `json:"created_at"`
	UpdatedAt utils.JsonTime `json:"updated_at"`
}

type ShowAPIKeys struct {
	APIKeys
	ApiKey string `json:"api_key"`
}

type CreateAPIKeyRes struct {
	BasicRes
	Data *RbacApiKey `json:"data"`
}

type ListAPIKeysRes struct {
	BasicRes
	Data []RbacApiKey `json:"data"`
}

type RbacApiKey struct {
	Id        uint64 `json:"id"`
	AccessKey string `json:"access_key,omitempty"`
	SecretKey string `json:"secret_key,omitempty"`
	//Base64Key    string         `json:"base64_key,omitempty"`
	Source       string         `json:"source"`
	Name         string         `json:"name"`
	CreatedBy    string         `json:"created_by"`
	UpdatedBy    string         `json:"updated_by"`
	CreatedAt    utils.JsonTime `json:"created_at"`
	UpdatedAt    utils.JsonTime `json:"updated_at"`
	Role         string         `json:"role"`
	RateLimitRpm int            `json:"rate_limit_rpm"`
	TTLInMin     int            `json:"ttl_in_min"`
	expireTs     *time.Time     `json:"-"`
}

func (k *RbacApiKey) IsExpired() bool {
	return k.TTLInMin < 0
}

func (k *RbacApiKey) SetExpireInfo(ts *timestamppb.Timestamp) {
	// init to never expire
	k.TTLInMin = 0
	k.expireTs = nil
	if ts != nil {
		expireTime := ts.AsTime()
		k.expireTs = &expireTime
		ttlInSec := int(time.Until(expireTime) / time.Second)
		if ttlInSec > 0 {
			k.TTLInMin = (ttlInSec + 59) / 60 // roundup
		} else {
			k.TTLInMin = -1
		}
	}
}

func (k *RbacApiKey) GetExpirePbTs() *timestamppb.Timestamp {
	if k.expireTs == nil {
		return nil
	}
	return timestamppb.New(*k.expireTs)
}
