package user

import (
	"context"
	"strings"

	logicCommon "github.com/perfect-panel/server/internal/logic/common"
	"github.com/perfect-panel/server/internal/model/user"
	"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/tool"
	"github.com/perfect-panel/server/pkg/xerr"
	"github.com/pkg/errors"
)

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

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

func (l *GetUserDetailLogic) GetUserDetail(req *types.GetDetailRequest) (*types.User, error) {
	resp := types.User{}
	userInfo, err := l.svcCtx.UserModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "get user detail error: %v", err.Error())
	}
	tool.DeepCopy(&resp, userInfo)
	for i, d := range userInfo.UserDevices {
		if i < len(resp.UserDevices) {
			resp.UserDevices[i].DeviceNo = tool.DeviceIdToHash(d.Id)
		}
	}
	if referCode := strings.TrimSpace(resp.ReferCode); referCode != "" {
		resp.ShareLink = logicCommon.NewInviteLinkResolver(l.ctx, l.svcCtx).ResolveInviteLink(referCode)
	}

	type familyRelation struct {
		FamilyId     int64
		Role         uint8
		FamilyStatus uint8
		OwnerUserId  int64
		MaxMembers   int64
	}

	var relation familyRelation
	relationErr := l.svcCtx.DB.WithContext(l.ctx).
		Table("user_family_member").
		Select("user_family_member.family_id, user_family_member.role, user_family.status as family_status, user_family.owner_user_id, user_family.max_members").
		Joins("JOIN user_family ON user_family.id = user_family_member.family_id AND user_family.deleted_at IS NULL").
		Where("user_family_member.user_id = ? AND user_family_member.deleted_at IS NULL AND user_family_member.status = ?", req.Id, user.FamilyMemberActive).
		First(&relation).Error
	if relationErr == nil {
		resp.FamilyJoined = true
		resp.FamilyId = relation.FamilyId
		resp.FamilyRole = relation.Role
		resp.FamilyOwnerUserId = relation.OwnerUserId
		resp.FamilyMaxMembers = relation.MaxMembers
		if relation.FamilyStatus == user.FamilyStatusActive {
			resp.FamilyStatus = "active"
		} else {
			resp.FamilyStatus = "disabled"
		}
		if relation.Role == user.FamilyRoleOwner {
			resp.FamilyRoleName = "owner"
		} else if relation.Role == user.FamilyRoleMember {
			resp.FamilyRoleName = "member"
		}

		type familyCount struct {
			Count int64
		}
		var count familyCount
		if countErr := l.svcCtx.DB.WithContext(l.ctx).
			Table("user_family_member").
			Select("COUNT(1) as count").
			Where("family_id = ? AND status = ? AND deleted_at IS NULL", relation.FamilyId, user.FamilyMemberActive).
			Scan(&count).Error; countErr == nil {
			resp.FamilyMemberCount = count.Count
		}
	}

	return &resp, nil
}
