package domain

import (
	"time"

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

// ProviderType defines the type of the identity provider.
type ProviderType string

const (
	ProviderTypeOIDC ProviderType = "oidc"
	ProviderTypeSAML ProviderType = "saml"
)

// IdentityProviderConfig stores the configuration for an external Identity Provider.
type IdentityProviderConfig struct {
	ID           string       `gorm:"primaryKey;type:uuid;default:gen_random_uuid()" json:"id"`
	ClientID     string       `gorm:"type:uuid;not null;index" json:"client_id"` // Replaces TenantID
	ProviderType ProviderType `gorm:"type:varchar(10);not null" json:"provider_type"`
	DisplayName  string       `gorm:"not null" json:"display_name"`
	Status       string       `gorm:"default:'active'" json:"status"`

	// OIDC Specific Fields
	IssuerURL        *string `gorm:"null" json:"issuer_url,omitempty"`
	OIDCClientID     *string `gorm:"null" json:"oidc_client_id,omitempty"`     // Renamed from ClientID
	OIDCClientSecret *string `gorm:"null" json:"oidc_client_secret,omitempty"` // Renamed from ClientSecret
	// Scopes are space-separated
	Scopes *string `gorm:"null" json:"scopes,omitempty"`

	// SAML Specific Fields
	MetadataURL *string `gorm:"null" json:"metadata_url,omitempty"`
	MetadataXML *string `gorm:"type:text;null" json:"metadata_xml,omitempty"`
	EntityID    *string `gorm:"null" json:"entity_id,omitempty"`
	AcsURL      *string `gorm:"null" json:"acs_url,omitempty"`

	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 (idc *IdentityProviderConfig) BeforeCreate(tx *gorm.DB) (err error) {
	if idc.ID == "" {
		idc.ID = uuid.NewString()
	}
	return
}
