package admin

import (
	"context"
	"fmt"

	"bindbox-game/internal/repository/mysql/model"

	"gorm.io/gorm"
)

type ListInput struct {
	Username string
	Nickname string
	Page     int
	PageSize int
}

func (s *service) List(ctx context.Context, in ListInput) ([]*model.Admin, int64, error) {
	query := s.readDB.Admin.WithContext(ctx)
	if in.Username != "" {
		query = query.Where(s.readDB.Admin.Username.Like(fmt.Sprintf("%%%s%%", in.Username)))
	}
	if in.Nickname != "" {
		query = query.Where(s.readDB.Admin.Nickname.Like(fmt.Sprintf("%%%s%%", in.Nickname)))
	}

	listQueryDB := query.Session(&gorm.Session{})
	countQueryDB := query.Session(&gorm.Session{})

	resultData, err := listQueryDB.
		Order(s.readDB.Admin.ID.Desc()).
		Limit(in.PageSize).
		Offset((in.Page - 1) * in.PageSize).Find()
	if err != nil {
		return nil, 0, err
	}

	count, err := countQueryDB.Count()
	if err != nil {
		return nil, 0, err
	}

	return resultData, count, nil
}
