// Code generated by ent, DO NOT EDIT.

package ent

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

	"entgo.io/ent"
	"entgo.io/ent/dialect/sql"
	"github.com/Wei-Shaw/sub2api/ent/apikey"
	"github.com/Wei-Shaw/sub2api/ent/group"
	"github.com/Wei-Shaw/sub2api/ent/user"
)

// APIKey is the model entity for the APIKey schema.
type APIKey struct {
	config `json:"-"`
	// ID of the ent.
	ID int64 `json:"id,omitempty"`
	// CreatedAt holds the value of the "created_at" field.
	CreatedAt time.Time `json:"created_at,omitempty"`
	// UpdatedAt holds the value of the "updated_at" field.
	UpdatedAt time.Time `json:"updated_at,omitempty"`
	// DeletedAt holds the value of the "deleted_at" field.
	DeletedAt *time.Time `json:"deleted_at,omitempty"`
	// UserID holds the value of the "user_id" field.
	UserID int64 `json:"user_id,omitempty"`
	// Key holds the value of the "key" field.
	Key string `json:"key,omitempty"`
	// Name holds the value of the "name" field.
	Name string `json:"name,omitempty"`
	// GroupID holds the value of the "group_id" field.
	GroupID *int64 `json:"group_id,omitempty"`
	// Status holds the value of the "status" field.
	Status string `json:"status,omitempty"`
	// Last usage time of this API key
	LastUsedAt *time.Time `json:"last_used_at,omitempty"`
	// Allowed IPs/CIDRs, e.g. ["192.168.1.100", "10.0.0.0/8"]
	IPWhitelist []string `json:"ip_whitelist,omitempty"`
	// Blocked IPs/CIDRs
	IPBlacklist []string `json:"ip_blacklist,omitempty"`
	// Quota limit in USD for this API key (0 = unlimited)
	Quota float64 `json:"quota,omitempty"`
	// Used quota amount in USD
	QuotaUsed float64 `json:"quota_used,omitempty"`
	// Expiration time for this API key (null = never expires)
	ExpiresAt *time.Time `json:"expires_at,omitempty"`
	// Rate limit in USD per 5 hours (0 = unlimited)
	RateLimit5h float64 `json:"rate_limit_5h,omitempty"`
	// Rate limit in USD per day (0 = unlimited)
	RateLimit1d float64 `json:"rate_limit_1d,omitempty"`
	// Rate limit in USD per 7 days (0 = unlimited)
	RateLimit7d float64 `json:"rate_limit_7d,omitempty"`
	// Used amount in USD for the current 5h window
	Usage5h float64 `json:"usage_5h,omitempty"`
	// Used amount in USD for the current 1d window
	Usage1d float64 `json:"usage_1d,omitempty"`
	// Used amount in USD for the current 7d window
	Usage7d float64 `json:"usage_7d,omitempty"`
	// Start time of the current 5h rate limit window
	Window5hStart *time.Time `json:"window_5h_start,omitempty"`
	// Start time of the current 1d rate limit window
	Window1dStart *time.Time `json:"window_1d_start,omitempty"`
	// Start time of the current 7d rate limit window
	Window7dStart *time.Time `json:"window_7d_start,omitempty"`
	// 是否对该 API Key 的请求体进行存储捕获
	CaptureRequests bool `json:"capture_requests,omitempty"`
	// Edges holds the relations/edges for other nodes in the graph.
	// The values are being populated by the APIKeyQuery when eager-loading is set.
	Edges        APIKeyEdges `json:"edges"`
	selectValues sql.SelectValues
}

// APIKeyEdges holds the relations/edges for other nodes in the graph.
type APIKeyEdges struct {
	// User holds the value of the user edge.
	User *User `json:"user,omitempty"`
	// Group holds the value of the group edge.
	Group *Group `json:"group,omitempty"`
	// UsageLogs holds the value of the usage_logs edge.
	UsageLogs []*UsageLog `json:"usage_logs,omitempty"`
	// loadedTypes holds the information for reporting if a
	// type was loaded (or requested) in eager-loading or not.
	loadedTypes [3]bool
}

// UserOrErr returns the User value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e APIKeyEdges) UserOrErr() (*User, error) {
	if e.User != nil {
		return e.User, nil
	} else if e.loadedTypes[0] {
		return nil, &NotFoundError{label: user.Label}
	}
	return nil, &NotLoadedError{edge: "user"}
}

// GroupOrErr returns the Group value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e APIKeyEdges) GroupOrErr() (*Group, error) {
	if e.Group != nil {
		return e.Group, nil
	} else if e.loadedTypes[1] {
		return nil, &NotFoundError{label: group.Label}
	}
	return nil, &NotLoadedError{edge: "group"}
}

// UsageLogsOrErr returns the UsageLogs value or an error if the edge
// was not loaded in eager-loading.
func (e APIKeyEdges) UsageLogsOrErr() ([]*UsageLog, error) {
	if e.loadedTypes[2] {
		return e.UsageLogs, nil
	}
	return nil, &NotLoadedError{edge: "usage_logs"}
}

// scanValues returns the types for scanning values from sql.Rows.
func (*APIKey) scanValues(columns []string) ([]any, error) {
	values := make([]any, len(columns))
	for i := range columns {
		switch columns[i] {
		case apikey.FieldIPWhitelist, apikey.FieldIPBlacklist:
			values[i] = new([]byte)
		case apikey.FieldCaptureRequests:
			values[i] = new(sql.NullBool)
		case apikey.FieldQuota, apikey.FieldQuotaUsed, apikey.FieldRateLimit5h, apikey.FieldRateLimit1d, apikey.FieldRateLimit7d, apikey.FieldUsage5h, apikey.FieldUsage1d, apikey.FieldUsage7d:
			values[i] = new(sql.NullFloat64)
		case apikey.FieldID, apikey.FieldUserID, apikey.FieldGroupID:
			values[i] = new(sql.NullInt64)
		case apikey.FieldKey, apikey.FieldName, apikey.FieldStatus:
			values[i] = new(sql.NullString)
		case apikey.FieldCreatedAt, apikey.FieldUpdatedAt, apikey.FieldDeletedAt, apikey.FieldLastUsedAt, apikey.FieldExpiresAt, apikey.FieldWindow5hStart, apikey.FieldWindow1dStart, apikey.FieldWindow7dStart:
			values[i] = new(sql.NullTime)
		default:
			values[i] = new(sql.UnknownType)
		}
	}
	return values, nil
}

// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the APIKey fields.
func (_m *APIKey) assignValues(columns []string, values []any) error {
	if m, n := len(values), len(columns); m < n {
		return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
	}
	for i := range columns {
		switch columns[i] {
		case apikey.FieldID:
			value, ok := values[i].(*sql.NullInt64)
			if !ok {
				return fmt.Errorf("unexpected type %T for field id", value)
			}
			_m.ID = int64(value.Int64)
		case apikey.FieldCreatedAt:
			if value, ok := values[i].(*sql.NullTime); !ok {
				return fmt.Errorf("unexpected type %T for field created_at", values[i])
			} else if value.Valid {
				_m.CreatedAt = value.Time
			}
		case apikey.FieldUpdatedAt:
			if value, ok := values[i].(*sql.NullTime); !ok {
				return fmt.Errorf("unexpected type %T for field updated_at", values[i])
			} else if value.Valid {
				_m.UpdatedAt = value.Time
			}
		case apikey.FieldDeletedAt:
			if value, ok := values[i].(*sql.NullTime); !ok {
				return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
			} else if value.Valid {
				_m.DeletedAt = new(time.Time)
				*_m.DeletedAt = value.Time
			}
		case apikey.FieldUserID:
			if value, ok := values[i].(*sql.NullInt64); !ok {
				return fmt.Errorf("unexpected type %T for field user_id", values[i])
			} else if value.Valid {
				_m.UserID = value.Int64
			}
		case apikey.FieldKey:
			if value, ok := values[i].(*sql.NullString); !ok {
				return fmt.Errorf("unexpected type %T for field key", values[i])
			} else if value.Valid {
				_m.Key = value.String
			}
		case apikey.FieldName:
			if value, ok := values[i].(*sql.NullString); !ok {
				return fmt.Errorf("unexpected type %T for field name", values[i])
			} else if value.Valid {
				_m.Name = value.String
			}
		case apikey.FieldGroupID:
			if value, ok := values[i].(*sql.NullInt64); !ok {
				return fmt.Errorf("unexpected type %T for field group_id", values[i])
			} else if value.Valid {
				_m.GroupID = new(int64)
				*_m.GroupID = value.Int64
			}
		case apikey.FieldStatus:
			if value, ok := values[i].(*sql.NullString); !ok {
				return fmt.Errorf("unexpected type %T for field status", values[i])
			} else if value.Valid {
				_m.Status = value.String
			}
		case apikey.FieldLastUsedAt:
			if value, ok := values[i].(*sql.NullTime); !ok {
				return fmt.Errorf("unexpected type %T for field last_used_at", values[i])
			} else if value.Valid {
				_m.LastUsedAt = new(time.Time)
				*_m.LastUsedAt = value.Time
			}
		case apikey.FieldIPWhitelist:
			if value, ok := values[i].(*[]byte); !ok {
				return fmt.Errorf("unexpected type %T for field ip_whitelist", values[i])
			} else if value != nil && len(*value) > 0 {
				if err := json.Unmarshal(*value, &_m.IPWhitelist); err != nil {
					return fmt.Errorf("unmarshal field ip_whitelist: %w", err)
				}
			}
		case apikey.FieldIPBlacklist:
			if value, ok := values[i].(*[]byte); !ok {
				return fmt.Errorf("unexpected type %T for field ip_blacklist", values[i])
			} else if value != nil && len(*value) > 0 {
				if err := json.Unmarshal(*value, &_m.IPBlacklist); err != nil {
					return fmt.Errorf("unmarshal field ip_blacklist: %w", err)
				}
			}
		case apikey.FieldQuota:
			if value, ok := values[i].(*sql.NullFloat64); !ok {
				return fmt.Errorf("unexpected type %T for field quota", values[i])
			} else if value.Valid {
				_m.Quota = value.Float64
			}
		case apikey.FieldQuotaUsed:
			if value, ok := values[i].(*sql.NullFloat64); !ok {
				return fmt.Errorf("unexpected type %T for field quota_used", values[i])
			} else if value.Valid {
				_m.QuotaUsed = value.Float64
			}
		case apikey.FieldExpiresAt:
			if value, ok := values[i].(*sql.NullTime); !ok {
				return fmt.Errorf("unexpected type %T for field expires_at", values[i])
			} else if value.Valid {
				_m.ExpiresAt = new(time.Time)
				*_m.ExpiresAt = value.Time
			}
		case apikey.FieldRateLimit5h:
			if value, ok := values[i].(*sql.NullFloat64); !ok {
				return fmt.Errorf("unexpected type %T for field rate_limit_5h", values[i])
			} else if value.Valid {
				_m.RateLimit5h = value.Float64
			}
		case apikey.FieldRateLimit1d:
			if value, ok := values[i].(*sql.NullFloat64); !ok {
				return fmt.Errorf("unexpected type %T for field rate_limit_1d", values[i])
			} else if value.Valid {
				_m.RateLimit1d = value.Float64
			}
		case apikey.FieldRateLimit7d:
			if value, ok := values[i].(*sql.NullFloat64); !ok {
				return fmt.Errorf("unexpected type %T for field rate_limit_7d", values[i])
			} else if value.Valid {
				_m.RateLimit7d = value.Float64
			}
		case apikey.FieldUsage5h:
			if value, ok := values[i].(*sql.NullFloat64); !ok {
				return fmt.Errorf("unexpected type %T for field usage_5h", values[i])
			} else if value.Valid {
				_m.Usage5h = value.Float64
			}
		case apikey.FieldUsage1d:
			if value, ok := values[i].(*sql.NullFloat64); !ok {
				return fmt.Errorf("unexpected type %T for field usage_1d", values[i])
			} else if value.Valid {
				_m.Usage1d = value.Float64
			}
		case apikey.FieldUsage7d:
			if value, ok := values[i].(*sql.NullFloat64); !ok {
				return fmt.Errorf("unexpected type %T for field usage_7d", values[i])
			} else if value.Valid {
				_m.Usage7d = value.Float64
			}
		case apikey.FieldWindow5hStart:
			if value, ok := values[i].(*sql.NullTime); !ok {
				return fmt.Errorf("unexpected type %T for field window_5h_start", values[i])
			} else if value.Valid {
				_m.Window5hStart = new(time.Time)
				*_m.Window5hStart = value.Time
			}
		case apikey.FieldWindow1dStart:
			if value, ok := values[i].(*sql.NullTime); !ok {
				return fmt.Errorf("unexpected type %T for field window_1d_start", values[i])
			} else if value.Valid {
				_m.Window1dStart = new(time.Time)
				*_m.Window1dStart = value.Time
			}
		case apikey.FieldWindow7dStart:
			if value, ok := values[i].(*sql.NullTime); !ok {
				return fmt.Errorf("unexpected type %T for field window_7d_start", values[i])
			} else if value.Valid {
				_m.Window7dStart = new(time.Time)
				*_m.Window7dStart = value.Time
			}
		case apikey.FieldCaptureRequests:
			if value, ok := values[i].(*sql.NullBool); !ok {
				return fmt.Errorf("unexpected type %T for field capture_requests", values[i])
			} else if value.Valid {
				_m.CaptureRequests = value.Bool
			}
		default:
			_m.selectValues.Set(columns[i], values[i])
		}
	}
	return nil
}

// Value returns the ent.Value that was dynamically selected and assigned to the APIKey.
// This includes values selected through modifiers, order, etc.
func (_m *APIKey) Value(name string) (ent.Value, error) {
	return _m.selectValues.Get(name)
}

// QueryUser queries the "user" edge of the APIKey entity.
func (_m *APIKey) QueryUser() *UserQuery {
	return NewAPIKeyClient(_m.config).QueryUser(_m)
}

// QueryGroup queries the "group" edge of the APIKey entity.
func (_m *APIKey) QueryGroup() *GroupQuery {
	return NewAPIKeyClient(_m.config).QueryGroup(_m)
}

// QueryUsageLogs queries the "usage_logs" edge of the APIKey entity.
func (_m *APIKey) QueryUsageLogs() *UsageLogQuery {
	return NewAPIKeyClient(_m.config).QueryUsageLogs(_m)
}

// Update returns a builder for updating this APIKey.
// Note that you need to call APIKey.Unwrap() before calling this method if this APIKey
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *APIKey) Update() *APIKeyUpdateOne {
	return NewAPIKeyClient(_m.config).UpdateOne(_m)
}

// Unwrap unwraps the APIKey entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *APIKey) Unwrap() *APIKey {
	_tx, ok := _m.config.driver.(*txDriver)
	if !ok {
		panic("ent: APIKey is not a transactional entity")
	}
	_m.config.driver = _tx.drv
	return _m
}

// String implements the fmt.Stringer.
func (_m *APIKey) String() string {
	var builder strings.Builder
	builder.WriteString("APIKey(")
	builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
	builder.WriteString("created_at=")
	builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
	builder.WriteString(", ")
	builder.WriteString("updated_at=")
	builder.WriteString(_m.UpdatedAt.Format(time.ANSIC))
	builder.WriteString(", ")
	if v := _m.DeletedAt; v != nil {
		builder.WriteString("deleted_at=")
		builder.WriteString(v.Format(time.ANSIC))
	}
	builder.WriteString(", ")
	builder.WriteString("user_id=")
	builder.WriteString(fmt.Sprintf("%v", _m.UserID))
	builder.WriteString(", ")
	builder.WriteString("key=")
	builder.WriteString(_m.Key)
	builder.WriteString(", ")
	builder.WriteString("name=")
	builder.WriteString(_m.Name)
	builder.WriteString(", ")
	if v := _m.GroupID; v != nil {
		builder.WriteString("group_id=")
		builder.WriteString(fmt.Sprintf("%v", *v))
	}
	builder.WriteString(", ")
	builder.WriteString("status=")
	builder.WriteString(_m.Status)
	builder.WriteString(", ")
	if v := _m.LastUsedAt; v != nil {
		builder.WriteString("last_used_at=")
		builder.WriteString(v.Format(time.ANSIC))
	}
	builder.WriteString(", ")
	builder.WriteString("ip_whitelist=")
	builder.WriteString(fmt.Sprintf("%v", _m.IPWhitelist))
	builder.WriteString(", ")
	builder.WriteString("ip_blacklist=")
	builder.WriteString(fmt.Sprintf("%v", _m.IPBlacklist))
	builder.WriteString(", ")
	builder.WriteString("quota=")
	builder.WriteString(fmt.Sprintf("%v", _m.Quota))
	builder.WriteString(", ")
	builder.WriteString("quota_used=")
	builder.WriteString(fmt.Sprintf("%v", _m.QuotaUsed))
	builder.WriteString(", ")
	if v := _m.ExpiresAt; v != nil {
		builder.WriteString("expires_at=")
		builder.WriteString(v.Format(time.ANSIC))
	}
	builder.WriteString(", ")
	builder.WriteString("rate_limit_5h=")
	builder.WriteString(fmt.Sprintf("%v", _m.RateLimit5h))
	builder.WriteString(", ")
	builder.WriteString("rate_limit_1d=")
	builder.WriteString(fmt.Sprintf("%v", _m.RateLimit1d))
	builder.WriteString(", ")
	builder.WriteString("rate_limit_7d=")
	builder.WriteString(fmt.Sprintf("%v", _m.RateLimit7d))
	builder.WriteString(", ")
	builder.WriteString("usage_5h=")
	builder.WriteString(fmt.Sprintf("%v", _m.Usage5h))
	builder.WriteString(", ")
	builder.WriteString("usage_1d=")
	builder.WriteString(fmt.Sprintf("%v", _m.Usage1d))
	builder.WriteString(", ")
	builder.WriteString("usage_7d=")
	builder.WriteString(fmt.Sprintf("%v", _m.Usage7d))
	builder.WriteString(", ")
	if v := _m.Window5hStart; v != nil {
		builder.WriteString("window_5h_start=")
		builder.WriteString(v.Format(time.ANSIC))
	}
	builder.WriteString(", ")
	if v := _m.Window1dStart; v != nil {
		builder.WriteString("window_1d_start=")
		builder.WriteString(v.Format(time.ANSIC))
	}
	builder.WriteString(", ")
	if v := _m.Window7dStart; v != nil {
		builder.WriteString("window_7d_start=")
		builder.WriteString(v.Format(time.ANSIC))
	}
	builder.WriteString(", ")
	builder.WriteString("capture_requests=")
	builder.WriteString(fmt.Sprintf("%v", _m.CaptureRequests))
	builder.WriteByte(')')
	return builder.String()
}

// APIKeys is a parsable slice of APIKey.
type APIKeys []*APIKey
