package models

import (
	"time"

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

// FederatedIdentity represents a federated identity (OAuth, etc.)
type FederatedIdentity struct {
	ID           uuid.UUID      `gorm:"type:uuid;primaryKey" json:"id"`
	UserID       uuid.UUID      `gorm:"type:uuid;not null;index" json:"user_id"`
	Provider     string         `gorm:"not null" json:"provider" validate:"required,oneof=google github facebook twitter"`
	ProviderID   string         `gorm:"not null" json:"provider_id"`
	Email        string         `json:"email"`
	DisplayName  string         `json:"display_name"`
	AvatarURL    string         `json:"avatar_url"`
	AccessToken  string         `gorm:"type:text" json:"-"`
	RefreshToken string         `gorm:"type:text" json:"-"`
	ExpiresAt    *time.Time     `json:"expires_at"`
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
	DeletedAt    gorm.DeletedAt `gorm:"index" json:"-"`

	// Relations
	User User `gorm:"foreignKey:UserID;constraint:OnDelete:CASCADE" json:"-"`
}

// BeforeCreate hook to generate UUID if not set
func (f *FederatedIdentity) BeforeCreate(tx *gorm.DB) error {
	if f.ID == uuid.Nil {
		f.ID = uuid.New()
	}
	return nil
}

// TableName returns the table name for the FederatedIdentity model
func (FederatedIdentity) TableName() string {
	return "federated_identities"
}
