package activity_log

import (
	"Yimaru-Backend/internal/domain"
	"Yimaru-Backend/internal/ports"
	"context"
	"encoding/json"

	"go.uber.org/zap"
)

type Service struct {
	store  ports.ActivityLogStore
	logger *zap.Logger
}

func NewService(store ports.ActivityLogStore, logger *zap.Logger) *Service {
	return &Service{
		store:  store,
		logger: logger,
	}
}

func (s *Service) Record(ctx context.Context, log domain.ActivityLog) {
	if _, err := s.store.CreateActivityLog(ctx, log); err != nil {
		s.logger.Warn("failed to record activity log",
			zap.String("action", log.Action),
			zap.String("resource_type", log.ResourceType),
			zap.Error(err),
		)
	}
}

func (s *Service) List(ctx context.Context, filter domain.ActivityLogFilter) ([]domain.ActivityLog, int64, error) {
	return s.store.ListActivityLogs(ctx, filter)
}

func (s *Service) GetByID(ctx context.Context, id int64) (domain.ActivityLog, error) {
	return s.store.GetActivityLogByID(ctx, id)
}

func (s *Service) RecordAction(ctx context.Context, actorID *int64, actorRole *string, action domain.ActivityAction, resourceType domain.ResourceType, resourceID *int64, message string, metadata json.RawMessage, ip *string, userAgent *string) {
	s.Record(ctx, domain.ActivityLog{
		ActorID:      actorID,
		ActorRole:    actorRole,
		Action:       string(action),
		ResourceType: string(resourceType),
		ResourceID:   resourceID,
		Message:      &message,
		Metadata:     metadata,
		IPAddress:    ip,
		UserAgent:    userAgent,
	})
}
