package repository

import (
	"errors"

	"hyapp-admin-server/internal/model"
	"hyapp-admin-server/internal/security"

	"gorm.io/gorm"
)

func (s *Store) ListUsers(options ListOptions) ([]model.User, int64, error) {
	return s.ListUsersWithAccess(options, DataAccess{All: true})
}

func (s *Store) UsersByIDs(ids []uint) (map[uint]model.User, error) {
	usersByID := make(map[uint]model.User, len(ids))
	if len(ids) == 0 {
		return usersByID, nil
	}
	var users []model.User
	if err := s.db.Where("id IN ?", ids).Find(&users).Error; err != nil {
		return nil, err
	}
	for _, user := range users {
		usersByID[user.ID] = user
	}
	return usersByID, nil
}

func (s *Store) ListUsersWithAccess(options ListOptions, access DataAccess) ([]model.User, int64, error) {
	page, pageSize := normalizePage(options.Page, options.PageSize)
	query := s.db.Model(&model.User{}).Preload("Roles").Preload("TeamRecord")
	query = applyUserFilters(query, options)
	query = applyUserDataAccess(query, access)

	var total int64
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	var users []model.User
	err := query.Order(userSort(options.Sort)).Offset((page - 1) * pageSize).Limit(pageSize).Find(&users).Error
	return users, total, err
}

func (s *Store) ExportUsers(options ListOptions) ([]model.User, error) {
	return s.ExportUsersWithAccess(options, DataAccess{All: true})
}

func (s *Store) ExportUsersWithAccess(options ListOptions, access DataAccess) ([]model.User, error) {
	var users []model.User
	query := s.db.Model(&model.User{}).Preload("Roles").Preload("TeamRecord")
	query = applyUserFilters(query, options)
	query = applyUserDataAccess(query, access)
	err := query.Order(userSort(options.Sort)).Find(&users).Error
	return users, err
}

func (s *Store) CreateUser(user *model.User, roleIDs []uint) error {
	return s.db.Transaction(func(tx *gorm.DB) error {
		if err := tx.Create(user).Error; err != nil {
			return err
		}
		return replaceUserRoles(tx, user, roleIDs)
	})
}

func (s *Store) UpdateUser(userID uint, updates map[string]any, roleIDs *[]uint) (*model.User, error) {
	var user model.User
	if err := s.db.First(&user, userID).Error; err != nil {
		return nil, err
	}

	err := s.db.Transaction(func(tx *gorm.DB) error {
		if len(updates) > 0 {
			if err := tx.Model(&user).Updates(updates).Error; err != nil {
				return err
			}
		}
		if roleIDs != nil {
			if err := replaceUserRoles(tx, &user, *roleIDs); err != nil {
				return err
			}
		}
		return nil
	})
	if err != nil {
		return nil, err
	}

	return s.FindUserByID(userID)
}

func (s *Store) UpdateUserStatus(userID uint, status string) (*model.User, error) {
	if !validUserStatus(status) {
		return nil, errors.New("invalid user status")
	}
	return s.UpdateUser(userID, map[string]any{"status": status}, nil)
}

func (s *Store) BatchUpdateUserStatus(ids []uint, status string) error {
	if !validUserStatus(status) {
		return errors.New("invalid user status")
	}
	if len(ids) == 0 {
		return nil
	}
	return s.db.Model(&model.User{}).Where("id IN ?", ids).Update("status", status).Error
}

func (s *Store) ResetUserPassword(userID uint, password string) error {
	hash, err := security.HashPassword(password)
	if err != nil {
		return err
	}
	return s.db.Model(&model.User{}).Where("id = ?", userID).Update("password_hash", hash).Error
}
