package service

import (
	"fmt"
	"time"

	"x-agents/server/internal/model"
	"x-agents/server/internal/repository"

	"github.com/google/uuid"
)

type ApprovalService struct {
	auditRepo *repository.AuditRepository
}

func NewApprovalService(auditRepo *repository.AuditRepository) *ApprovalService {
	return &ApprovalService{auditRepo: auditRepo}
}

// CreateApprovalRequest 创建审批请求
func (s *ApprovalService) CreateApprovalRequest(
	toolName string,
	params map[string]interface{},
	userID string,
	agentID string,
	reason string,
) (*model.ToolApprovalRequest, error) {

	req := &model.ToolApprovalRequest{
		ID:       uuid.New().String(),
		ToolName: toolName,
		Params:   params,
		UserID:   userID,
		AgentID:  agentID,
		Reason:   reason,
		Status:   model.ApprovalStatusPending,
	}

	if err := s.auditRepo.CreateApproval(req); err != nil {
		return nil, err
	}

	return req, nil
}

// Approve 批准请求
func (s *ApprovalService) Approve(requestID, reviewedBy string) (*model.ToolApprovalRequest, error) {
	req, err := s.auditRepo.FindApprovalByID(requestID)
	if err != nil {
		return nil, fmt.Errorf("request not found: %w", err)
	}

	if req.Status != model.ApprovalStatusPending {
		return nil, fmt.Errorf("request already processed")
	}

	now := time.Now()
	req.Status = model.ApprovalStatusApproved
	req.ReviewedBy = &reviewedBy
	req.ReviewedAt = &now

	if err := s.auditRepo.UpdateApproval(req); err != nil {
		return nil, err
	}

	return req, nil
}

// Reject 拒绝请求
func (s *ApprovalService) Reject(requestID, reviewedBy string) (*model.ToolApprovalRequest, error) {
	req, err := s.auditRepo.FindApprovalByID(requestID)
	if err != nil {
		return nil, fmt.Errorf("request not found: %w", err)
	}

	if req.Status != model.ApprovalStatusPending {
		return nil, fmt.Errorf("request already processed")
	}

	now := time.Now()
	req.Status = model.ApprovalStatusRejected
	req.ReviewedBy = &reviewedBy
	req.ReviewedAt = &now

	if err := s.auditRepo.UpdateApproval(req); err != nil {
		return nil, err
	}

	return req, nil
}

// GetApproval 获取审批状态
func (s *ApprovalService) GetApproval(requestID string) (*model.ToolApprovalRequest, error) {
	return s.auditRepo.FindApprovalByID(requestID)
}

// GetPendingApprovals 获取待审批列表
func (s *ApprovalService) GetPendingApprovals() ([]model.ToolApprovalRequest, error) {
	return s.auditRepo.FindPendingApprovals()
}
