package user

import (
	"context"

	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/internal/types"
	"github.com/perfect-panel/server/pkg/logger"
	"github.com/perfect-panel/server/pkg/xerr"
	"github.com/pkg/errors"
)

type GetAdminUserInviteListLogic struct {
	logger.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetAdminUserInviteListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAdminUserInviteListLogic {
	return &GetAdminUserInviteListLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetAdminUserInviteListLogic) GetAdminUserInviteList(req *types.GetAdminUserInviteListRequest) (resp *types.GetAdminUserInviteListResponse, err error) {
	if req.Page < 1 {
		req.Page = 1
	}
	if req.Size < 1 {
		req.Size = 10
	}
	if req.Size > 100 {
		req.Size = 100
	}

	type InvitedUser struct {
		Id         int64  `gorm:"column:id"`
		Avatar     string `gorm:"column:avatar"`
		Identifier string `gorm:"column:identifier"`
		Enable     bool   `gorm:"column:enable"`
		CreatedAt  int64  `gorm:"column:created_at"`
	}

	var total int64
	baseQuery := l.svcCtx.DB.WithContext(l.ctx).
		Table("user u").
		Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId)

	if err = baseQuery.Count(&total).Error; err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count invited users failed: %v", err)
	}

	var rows []InvitedUser
	err = l.svcCtx.DB.WithContext(l.ctx).
		Table("user u").
		Select("u.id, u.avatar, u.enable, UNIX_TIMESTAMP(u.created_at) as created_at, COALESCE((SELECT uam.auth_identifier FROM user_auth_methods uam WHERE uam.user_id = u.id ORDER BY uam.id ASC LIMIT 1), '') as identifier").
		Where("u.referer_id = ? AND u.deleted_at IS NULL", req.UserId).
		Order("u.created_at DESC").
		Limit(req.Size).
		Offset((req.Page - 1) * req.Size).
		Scan(&rows).Error
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query invited users failed: %v", err)
	}

	list := make([]types.AdminInvitedUser, 0, len(rows))
	for _, r := range rows {
		list = append(list, types.AdminInvitedUser{
			Id:         r.Id,
			Avatar:     r.Avatar,
			Identifier: r.Identifier,
			Enable:     r.Enable,
			CreatedAt:  r.CreatedAt,
		})
	}

	return &types.GetAdminUserInviteListResponse{
		Total: total,
		List:  list,
	}, nil
}
