package model

import (
	"encoding/json"
	"time"
)

// AuditAction 审计动作
type AuditAction string

const (
	AuditActionLogin         AuditAction = "login"
	AuditActionLogout        AuditAction = "logout"
	AuditActionChat          AuditAction = "chat"
	AuditActionToolExecute   AuditAction = "tool_execute"
	AuditActionToolApprove   AuditAction = "tool_approve"
	AuditActionToolReject    AuditAction = "tool_reject"
	AuditActionAgentCreate   AuditAction = "agent_create"
	AuditActionAgentUpdate   AuditAction = "agent_update"
	AuditActionAgentDelete   AuditAction = "agent_delete"
)

// AuditLog 审计日志
type AuditLog struct {
	ID         string      `json:"id" gorm:"primaryKey"`
	UserID     string      `json:"user_id" gorm:"size:50;index"`
	AgentID    string      `json:"agent_id" gorm:"size:50;index"`
	Action     AuditAction `json:"action" gorm:"size:50;index"`
	Details    JSONMap     `json:"details" gorm:"type:jsonb"`
	Result     string      `json:"result" gorm:"size:20"` // success, failed, rejected
	IPAddress  string      `json:"ip_address" gorm:"size:45"`
	UserAgent  string      `json:"user_agent" gorm:"size:255"`
	CreatedAt  time.Time   `json:"created_at" gorm:"index"`
}

// ApprovalStatus 审批状态
type ApprovalStatus string

const (
	ApprovalStatusPending   ApprovalStatus = "pending"
	ApprovalStatusApproved ApprovalStatus = "approved"
	ApprovalStatusRejected ApprovalStatus = "rejected"
)

// ToolApprovalRequest 工具审批请求
type ToolApprovalRequest struct {
	ID          string          `json:"id" gorm:"primaryKey"`
	ToolName    string          `json:"tool_name" gorm:"size:100;index"`
	Params      JSONMap         `json:"params" gorm:"type:jsonb"`
	UserID      string          `json:"user_id" gorm:"size:50;index"`
	AgentID     string          `json:"agent_id" gorm:"size:50"`
	Reason      string          `json:"reason" gorm:"type:text"`
	Status      ApprovalStatus `json:"status" gorm:"size:20;default:'pending';index"`
	ReviewedBy  *string         `json:"reviewed_by" gorm:"size:50"`
	ReviewedAt  *time.Time     `json:"reviewed_at"`
	Result      *string        `json:"result" gorm:"type:text"` // 执行结果
	CreatedAt   time.Time      `json:"created_at" gorm:"index"`
	UpdatedAt   time.Time      `json:"updated_at"`
}

// JSONMap JSON数据映射
type JSONMap map[string]interface{}

func (j JSONMap) MarshalJSON() ([]byte, error) {
	if j == nil {
		return []byte("null"), nil
	}
	return json.Marshal(j)
}

func (j *JSONMap) UnmarshalJSON(data []byte) error {
	if j == nil {
		*j = make(map[string]interface{})
	}
	return json.Unmarshal(data, j)
}
