package repository import ( "baron-sso-backend/internal/domain" "context" "gorm.io/gorm" ) type UserRepository interface { Create(ctx context.Context, user *domain.User) error Update(ctx context.Context, user *domain.User) error FindByEmail(ctx context.Context, email string) (*domain.User, error) FindByID(ctx context.Context, id string) (*domain.User, error) FindByIDs(ctx context.Context, ids []string) ([]domain.User, error) ListByTenant(ctx context.Context, tenantID string) ([]domain.User, error) List(ctx context.Context, offset, limit int, search string) ([]domain.User, int64, error) } type userRepository struct { db *gorm.DB } func NewUserRepository(db *gorm.DB) UserRepository { return &userRepository{db: db} } func (r *userRepository) Create(ctx context.Context, user *domain.User) error { return r.db.WithContext(ctx).Create(user).Error } func (r *userRepository) Update(ctx context.Context, user *domain.User) error { return r.db.WithContext(ctx).Save(user).Error } func (r *userRepository) FindByEmail(ctx context.Context, email string) (*domain.User, error) { var user domain.User if err := r.db.WithContext(ctx).Preload("Tenant").Where("email = ?", email).First(&user).Error; err != nil { return nil, err } return &user, nil } func (r *userRepository) FindByID(ctx context.Context, id string) (*domain.User, error) { var user domain.User if err := r.db.WithContext(ctx).Preload("Tenant").Where("id = ?", id).First(&user).Error; err != nil { return nil, err } return &user, nil } func (r *userRepository) FindByIDs(ctx context.Context, ids []string) ([]domain.User, error) { var users []domain.User if len(ids) == 0 { return users, nil } if err := r.db.WithContext(ctx).Where("id IN ?", ids).Find(&users).Error; err != nil { return nil, err } return users, nil } func (r *userRepository) ListByTenant(ctx context.Context, tenantID string) ([]domain.User, error) { var users []domain.User if err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Find(&users).Error; err != nil { return nil, err } return users, nil } func (r *userRepository) List(ctx context.Context, offset, limit int, search string) ([]domain.User, int64, error) { var users []domain.User var total int64 db := r.db.WithContext(ctx).Model(&domain.User{}) if search != "" { searchTerm := "%" + search + "%" db = db.Where("email LIKE ? OR name LIKE ?", searchTerm, searchTerm) } if err := db.Count(&total).Error; err != nil { return nil, 0, err } if err := db.Offset(offset).Limit(limit).Find(&users).Error; err != nil { return nil, 0, err } return users, total, nil }