package domain

import (
	"time"

	"github.com/google/uuid"
	"gorm.io/gorm"
)

// ApiKey represents an internal API key for Machine-to-Machine communication.
type ApiKey struct {
	ID               string         `gorm:"primaryKey;type:uuid;default:gen_random_uuid()" json:"id"`
	Name             string         `gorm:"not null" json:"name"`
	ClientID         string         `gorm:"uniqueIndex;not null" json:"clientId"`
	ClientSecretHash string         `gorm:"not null" json:"-"`
	Scopes           string         `json:"scopes"` // Space or comma separated
	Status           string         `gorm:"default:'active'" json:"status"`
	LastUsedAt       *time.Time     `json:"lastUsedAt"`
	CreatedAt        time.Time      `json:"createdAt"`
	UpdatedAt        time.Time      `json:"updatedAt"`
	DeletedAt        gorm.DeletedAt `gorm:"index" json:"-"`
}

// BeforeCreate hook to generate UUID if not present.
func (k *ApiKey) BeforeCreate(tx *gorm.DB) (err error) {
	if k.ID == "" {
		k.ID = uuid.NewString()
	}
	return
}
