package domain

import (
	"time"

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

// KetoOutbox status
const (
	KetoOutboxStatusPending   = "pending"
	KetoOutboxStatusProcessed = "processed"
	KetoOutboxStatusFailed    = "failed"
)

// KetoOutbox action
const (
	KetoOutboxActionCreate = "CREATE"
	KetoOutboxActionDelete = "DELETE"
)

// KetoOutbox represents a Keto relationship tuple update event.
type KetoOutbox struct {
	ID          string     `gorm:"primaryKey;type:uuid;default:gen_random_uuid()" json:"id"`
	Namespace   string     `gorm:"not null" json:"namespace"`
	Object      string     `gorm:"not null" json:"object"`
	Relation    string     `gorm:"not null" json:"relation"`
	Subject     string     `gorm:"not null" json:"subject"` // format: "User:ID" or "Tenant:ID#members"
	Action      string     `gorm:"not null" json:"action"`  // CREATE, DELETE
	Status      string     `gorm:"default:'pending';index" json:"status"`
	RetryCount  int        `gorm:"default:0" json:"retryCount"`
	LastError   string     `json:"lastError,omitempty"`
	CreatedAt   time.Time  `json:"createdAt"`
	UpdatedAt   time.Time  `json:"updatedAt"`
	ProcessedAt *time.Time `json:"processedAt,omitempty"`
}

func (ko *KetoOutbox) TableName() string {
	return "keto_outbox"
}

func (ko *KetoOutbox) BeforeCreate(tx *gorm.DB) (err error) {
	if ko.ID == "" {
		ko.ID = uuid.NewString()
	}
	return
}
