package repository

import (
	"baron-sso-backend/internal/domain"
	"context"

	"gorm.io/gorm"
)

type SharedLinkRepository interface {
	Create(ctx context.Context, link *domain.SharedLink) error
	FindByToken(ctx context.Context, token string) (*domain.SharedLink, error)
	FindByTenantID(ctx context.Context, tenantID string) ([]domain.SharedLink, error)
	Delete(ctx context.Context, id string) error
	Update(ctx context.Context, link *domain.SharedLink) error
}

type sharedLinkRepository struct {
	db *gorm.DB
}

func NewSharedLinkRepository(db *gorm.DB) SharedLinkRepository {
	return &sharedLinkRepository{db: db}
}

func (r *sharedLinkRepository) Create(ctx context.Context, link *domain.SharedLink) error {
	return r.db.WithContext(ctx).Create(link).Error
}

func (r *sharedLinkRepository) FindByToken(ctx context.Context, token string) (*domain.SharedLink, error) {
	var link domain.SharedLink
	err := r.db.WithContext(ctx).Where("token = ? AND is_active = ?", token, true).First(&link).Error
	if err != nil {
		return nil, err
	}
	return &link, nil
}

func (r *sharedLinkRepository) FindByTenantID(ctx context.Context, tenantID string) ([]domain.SharedLink, error) {
	var links []domain.SharedLink
	err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Find(&links).Error
	return links, err
}

func (r *sharedLinkRepository) Delete(ctx context.Context, id string) error {
	return r.db.WithContext(ctx).Delete(&domain.SharedLink{}, "id = ?", id).Error
}

func (r *sharedLinkRepository) Update(ctx context.Context, link *domain.SharedLink) error {
	return r.db.WithContext(ctx).Save(link).Error
}
