package service import ( "context" "errors" "fmt" "github.com/gochat/gochat/internal/model" "github.com/gochat/gochat/internal/repository" applogger "github.com/gochat/gochat/pkg/logger" pkgvalidator "github.com/gochat/gochat/pkg/validator" "gorm.io/gorm" ) // AgentService implements business logic for Agent CRUD operations. // Reference: Chatwoot app/controllers/api/v1/accounts/agents_controller.rb // An "agent" in Chatwoot is a User with an AccountUser association in a specific account. type AgentService struct { agentRepo *repository.AgentRepo db *gorm.DB } // NewAgentService creates a new Agent service. func NewAgentService(agentRepo *repository.AgentRepo, db *gorm.DB) *AgentService { return &AgentService{agentRepo: agentRepo, db: db} } // CreateAgentRequest is the DTO for creating/adding an agent to an account. // Reference: Chatwoot agents_controller.rb#create → new_agent_params (email, name, role, availability, auto_offline) type CreateAgentRequest struct { Email string `json:"email" validate:"required,email"` Name string `json:"name" validate:"required,min=1"` Role string `json:"role" validate:"omitempty,oneof=agent administrator"` Availability string `json:"availability" validate:"omitempty,oneof=online offline busy"` AutoOffline bool `json:"auto_offline"` } // UpdateAgentRequest is the DTO for updating an agent. // Reference: Chatwoot agents_controller.rb#update → agent_params (name on User, role/availability/auto_offline on AccountUser) type UpdateAgentRequest struct { Name string `json:"name,omitempty" validate:"omitempty,min=1"` Role string `json:"role,omitempty" validate:"omitempty,oneof=agent administrator"` Availability string `json:"availability,omitempty" validate:"omitempty,oneof=online offline busy"` AutoOffline bool `json:"auto_offline"` } // BulkCreateAgentRequest is the DTO for bulk creating agents. // Reference: Chatwoot agents_controller.rb#bulk_create → params[:emails] type BulkCreateAgentRequest struct { Emails []string `json:"emails" validate:"required,min=1,dive,email"` } // List retrieves all agents for an account with pagination. func (s *AgentService) List(ctx context.Context, accountID uint, offset, limit int) ([]repository.AgentDetail, int64, error) { return s.agentRepo.ListByAccount(ctx, accountID, offset, limit) } // Get retrieves a single agent by user ID scoped to an account. func (s *AgentService) Get(ctx context.Context, userID, accountID uint) (*repository.AgentDetail, error) { return s.agentRepo.FindAgentByID(ctx, userID, accountID) } // Create adds an agent (user) to an account. // Reference: Chatwoot AgentBuilder — finds or creates User, then creates AccountUser. func (s *AgentService) Create(ctx context.Context, accountID uint, inviterID uint, req CreateAgentRequest) (*repository.AgentDetail, error) { if err := pkgvalidator.ValidateStruct(req); err != nil { return nil, fmt.Errorf("validation: %w", err) } role := req.Role if role == "" { role = "agent" } availability := req.Availability if availability == "" { availability = "offline" } detail, err := s.agentRepo.CreateAgent(ctx, accountID, inviterID, req.Name, req.Email, role, availability, req.AutoOffline) if err != nil { if errors.Is(err, repository.ErrAlreadyMember) { return nil, repository.ErrAlreadyMember } applogger.L().Errorf("AgentService.Create: %v", err) return nil, err } return detail, nil } // Update modifies an agent's details (name on User, role/availability on AccountUser). func (s *AgentService) Update(ctx context.Context, userID, accountID uint, req UpdateAgentRequest) (*repository.AgentDetail, error) { if err := pkgvalidator.ValidateStruct(req); err != nil { return nil, fmt.Errorf("validation: %w", err) } return s.agentRepo.UpdateAgent(ctx, userID, accountID, req.Name, req.Role, req.Availability, req.AutoOffline) } // Delete removes an agent from an account (deletes AccountUser, optionally deletes User). func (s *AgentService) Delete(ctx context.Context, userID, accountID uint) error { return s.agentRepo.DeleteAgent(ctx, userID, accountID) } // BulkCreate adds multiple agents to an account by email. // Reference: Chatwoot agents_controller.rb#bulk_create — iterates emails, creates AgentBuilder for each. // Silently skips emails that fail (duplicate, etc.). func (s *AgentService) BulkCreate(ctx context.Context, accountID uint, inviterID uint, req BulkCreateAgentRequest) ([]repository.AgentDetail, error) { if err := pkgvalidator.ValidateStruct(req); err != nil { return nil, fmt.Errorf("validation: %w", err) } return s.agentRepo.BulkCreateAgents(ctx, accountID, inviterID, req.Emails) } // AvailableAgentCount returns the number of additional agents that can be added to an account. // Reference: Chatwoot agents_controller.rb#available_agent_count — usage_limits[:agents] - agents.count // Returns -1 if no limit is set (0 = unlimited in our convention). func (s *AgentService) AvailableAgentCount(ctx context.Context, accountID uint) (int, error) { var account model.Account if err := s.db.WithContext(ctx).First(&account, accountID).Error; err != nil { return 0, fmt.Errorf("get account: %w", err) } currentCount, err := s.agentRepo.CountByAccount(ctx, accountID) if err != nil { return 0, fmt.Errorf("count agents: %w", err) } // AgentLimit=0 means unlimited (no restriction) if account.AgentLimit == 0 { return -1, nil } available := account.AgentLimit - int(currentCount) if available < 0 { available = 0 } return available, nil } // CanAddAgent checks whether an account can add at least one more agent. // Reference: Chatwoot agents_controller.rb#can_add_agent? — available_agent_count.positive? func (s *AgentService) CanAddAgent(ctx context.Context, accountID uint) (bool, error) { available, err := s.AvailableAgentCount(ctx, accountID) if err != nil { return false, err } // -1 means unlimited return available < 0 || available > 0, nil } // CanAddAgents checks whether an account can add N more agents. // Reference: Chatwoot agents_controller.rb#validate_limit_for_bulk_create func (s *AgentService) CanAddAgents(ctx context.Context, accountID uint, count int) (bool, error) { available, err := s.AvailableAgentCount(ctx, accountID) if err != nil { return false, err } // -1 means unlimited return available < 0 || available >= count, nil }