//
// Copyright (C) 2024 veypi <i@veypi.com>
// 2025-03-04 16:08:06
// Distributed under terms of the MIT license.
//

package models

import (
	"time"

	"github.com/veypi/vigo"
)

// OAuthClient OAuth2.0 客户端
type OAuthClient struct {
	vigo.Model
	ClientID      string `json:"client_id" gorm:"uniqueIndex;size:100;not null"`
	ClientSecret  string `json:"-" gorm:"size:255;not null"`
	Name          string `json:"name" gorm:"size:100;not null"`
	Description   string `json:"description" gorm:"size:500"`
	RedirectURIs  string `json:"redirect_uris" gorm:"type:text"` // JSON数组
	AllowedScopes string `json:"allowed_scopes" gorm:"size:500"` // 空格分隔
	OwnerID       string `json:"owner_id" gorm:"not null"`
	Status        int    `json:"status" gorm:"default:1"`

	// 外键关联
	Owner User `json:"owner,omitempty" gorm:"foreignKey:OwnerID;references:ID"`
}

// OAuthAuthorizationCode OAuth2.0 授权码
type OAuthAuthorizationCode struct {
	vigo.Model
	Code                string    `json:"code" gorm:"uniqueIndex;size:100;not null"`
	ClientID            string    `json:"client_id" gorm:"index;not null"`
	UserID              string    `json:"user_id" gorm:"index;not null"`
	RedirectURI         string    `json:"redirect_uri" gorm:"size:500"`
	Scope               string    `json:"scope" gorm:"size:200"`
	CodeChallenge       string    `json:"-" gorm:"size:128"`
	CodeChallengeMethod string    `json:"-" gorm:"size:10"`
	ExpiresAt           time.Time `json:"expires_at"`
	Used                bool      `json:"used" gorm:"default:false"`

	// 外键关联
	Client OAuthClient `json:"client,omitempty" gorm:"foreignKey:ClientID;references:ID"`
	User   User        `json:"user,omitempty" gorm:"foreignKey:UserID;references:ID"`
}

// OAuthToken OAuth2.0 令牌
type OAuthToken struct {
	vigo.Model
	ClientID     string    `json:"client_id" gorm:"index;not null"`
	UserID       string    `json:"user_id" gorm:"index;not null"`
	AccessToken  string    `json:"-" gorm:"uniqueIndex;size:255;not null"`
	RefreshToken string    `json:"-" gorm:"uniqueIndex;size:255"`
	TokenType    string    `json:"token_type" gorm:"size:20;default:'Bearer'"`
	Scope        string    `json:"scope" gorm:"size:200"`
	ExpiresAt    time.Time `json:"expires_at"`
	Revoked      bool      `json:"revoked" gorm:"default:false"`

	// 外键关联
	Client OAuthClient `json:"client,omitempty" gorm:"foreignKey:ClientID;references:ID"`
	User   User        `json:"user,omitempty" gorm:"foreignKey:UserID;references:ID"`
}

// OAuthClientStatus 客户端状态
const (
	OAuthClientStatusDisabled = 0
	OAuthClientStatusActive   = 1
)
