package guild

import (
	"context"

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

func (s *service) ListGuilds(ctx context.Context, in ListGuildsInput) (items []*model.Guild, total int64, err error) {
	q := s.readDB.Guild.WithContext(ctx).ReadDB()
	if in.Name != "" {
		q = q.Where(s.readDB.Guild.Name.Like("%" + in.Name + "%"))
	}
	if in.IsOpen != nil {
		q = q.Where(s.readDB.Guild.IsOpen.Eq(*in.IsOpen))
	}
	if in.Status != nil {
		q = q.Where(s.readDB.Guild.Status.Eq(*in.Status))
	}
	if in.JoinMode != nil {
		q = q.Where(s.readDB.Guild.JoinMode.Eq(*in.JoinMode))
	}
	total, err = q.Count()
	if err != nil {
		return nil, 0, err
	}
	if in.Page <= 0 {
		in.Page = 1
	}
	if in.PageSize <= 0 {
		in.PageSize = 20
	}
	if in.PageSize > 100 {
		in.PageSize = 100
	}
	items, err = q.Order(s.readDB.Guild.ID.Desc()).Offset((in.Page - 1) * in.PageSize).Limit(in.PageSize).Find()
	if err != nil {
		return nil, 0, err
	}
	return items, total, nil
}
