package service

import (
	"baron-sso-backend/internal/domain"
	"baron-sso-backend/internal/repository"
	"context"
	"errors"
	"time"
)

type SharedLinkService interface {
	CreateLink(ctx context.Context, tenantID, name, description string, expiresAt *time.Time) (*domain.SharedLink, error)
	ValidateToken(ctx context.Context, token string) (*domain.SharedLink, error)
	GetLinksByTenant(ctx context.Context, tenantID string) ([]domain.SharedLink, error)
	DeactivateLink(ctx context.Context, id string) error
}

type sharedLinkService struct {
	repo repository.SharedLinkRepository
}

func NewSharedLinkService(repo repository.SharedLinkRepository) SharedLinkService {
	return &sharedLinkService{repo: repo}
}

func (s *sharedLinkService) CreateLink(ctx context.Context, tenantID, name, description string, expiresAt *time.Time) (*domain.SharedLink, error) {
	link := &domain.SharedLink{
		TenantID:    tenantID,
		Name:        name,
		Description: description,
		ExpiresAt:   expiresAt,
		IsActive:    true,
		AccessLevel: "READ_ONLY",
	}

	if err := s.repo.Create(ctx, link); err != nil {
		return nil, err
	}
	return link, nil
}

func (s *sharedLinkService) ValidateToken(ctx context.Context, token string) (*domain.SharedLink, error) {
	link, err := s.repo.FindByToken(ctx, token)
	if err != nil {
		return nil, errors.New("invalid or expired share link")
	}

	if !link.IsValid() {
		return nil, errors.New("share link has expired or is inactive")
	}

	return link, nil
}

func (s *sharedLinkService) GetLinksByTenant(ctx context.Context, tenantID string) ([]domain.SharedLink, error) {
	return s.repo.FindByTenantID(ctx, tenantID)
}

func (s *sharedLinkService) DeactivateLink(ctx context.Context, id string) error {
	// 실제 삭제 대신 비활성화 처리 (soft-delete와 유사)
	// 하지만 여기서는 간단히 활성 플래그만 끔
	return s.repo.Delete(ctx, id) // 리포지토리의 Delete는 GORM의 DeletedAt을 사용하여 soft-delete함
}
