package repository

import (
	"x-agents/server/internal/model"

	"gorm.io/gorm"
)

type AuditRepository struct {
	db *gorm.DB
}

func NewAuditRepository(db *gorm.DB) *AuditRepository {
	return &AuditRepository{db: db}
}

func (r *AuditRepository) Create(log *model.AuditLog) error {
	return r.db.Create(log).Error
}

func (r *AuditRepository) FindByUserID(userID string, limit int) ([]model.AuditLog, error) {
	var logs []model.AuditLog
	err := r.db.Where("user_id = ?", userID).Order("created_at DESC").Limit(limit).Find(&logs).Error
	return logs, err
}

func (r *AuditRepository) FindByAgentID(agentID string, limit int) ([]model.AuditLog, error) {
	var logs []model.AuditLog
	err := r.db.Where("agent_id = ?", agentID).Order("created_at DESC").Limit(limit).Find(&logs).Error
	return logs, err
}

// ToolApproval 工具审批仓储

func (r *AuditRepository) CreateApproval(req *model.ToolApprovalRequest) error {
	return r.db.Create(req).Error
}

func (r *AuditRepository) FindApprovalByID(id string) (*model.ToolApprovalRequest, error) {
	var req model.ToolApprovalRequest
	err := r.db.First(&req, "id = ?", id).Error
	if err != nil {
		return nil, err
	}
	return &req, nil
}

func (r *AuditRepository) FindPendingApprovals() ([]model.ToolApprovalRequest, error) {
	var reqs []model.ToolApprovalRequest
	err := r.db.Where("status = ?", model.ApprovalStatusPending).Order("created_at ASC").Find(&reqs).Error
	return reqs, err
}

func (r *AuditRepository) UpdateApproval(req *model.ToolApprovalRequest) error {
	return r.db.Save(req).Error
}
