package permission

import (
	"encoding/json"
	"time"
)

// RecordState 生命週期(啟用/停用/已刪除)
type RecordState int8

const (
	RecordInactive RecordState = iota // 停用
	RecordActive                      // 啟用
	RecordDeleted                     // 已刪除
)

func (s RecordState) IsActive() bool {
	return s == RecordActive
}

func (s RecordState) String() string {
	switch s {
	case RecordInactive:
		return "inactive"
	case RecordActive:
		return "active"
	case RecordDeleted:
		return "deleted"
	default:
		return "unknown"
	}
}

// Type 權限類型
type Type int8

func (pt Type) String() string {
	switch pt {
	case TypeBackend:
		return "backend"
	case TypeFrontend:
		return "frontend"
	default:
		return "unknown"
	}
}

const (
	TypeBackend  Type = 1 // 後台權限
	TypeFrontend Type = 2 // 前台權限
)

// AccessState  權限狀態
type AccessState string

const (
	Open  AccessState = "open"
	Close AccessState = "close"
)

// Permissions 權限集合 (name -> status)
type Permissions map[string]AccessState

// HasPermission 檢查是否有權限
func (p Permissions) HasPermission(name string) bool {
	status, ok := p[name]
	return ok && status == Open
}

// AddPermission 新增權限
func (p Permissions) AddPermission(name string) {
	p[name] = Open
}

// RemovePermission 移除權限
func (p Permissions) RemovePermission(name string) {
	delete(p, name)
}

// Merge 合併權限
func (p Permissions) Merge(other Permissions) {
	for name, status := range other {
		if status == Open {
			p[name] = Open
		}
	}
}

// TimeStamp MongoDB 時間戳記 (使用 int64 Unix timestamp)
type TimeStamp struct {
	CreateTime int64 `bson:"create_time" json:"create_time"`
	UpdateTime int64 `bson:"update_time" json:"update_time"`
}

// NewTimeStamp 建立新的時間戳記
func NewTimeStamp() TimeStamp {
	now := time.Now().Unix()
	return TimeStamp{
		CreateTime: now,
		UpdateTime: now,
	}
}

// UpdateTimestamp 更新時間戳記
func (t *TimeStamp) UpdateTimestamp() {
	t.UpdateTime = time.Now().Unix()
}

// MarshalJSON 自訂 JSON 序列化
func (t *TimeStamp) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		CreateTime string `json:"create_time"`
		UpdateTime string `json:"update_time"`
	}{
		CreateTime: time.Unix(t.CreateTime, 0).UTC().Format(time.RFC3339),
		UpdateTime: time.Unix(t.UpdateTime, 0).UTC().Format(time.RFC3339),
	})
}
