package user

import (
	"context"
	"errors"

	"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/constant"
	"github.com/perfect-panel/server/pkg/logger"
	"github.com/perfect-panel/server/pkg/tool"
	"gorm.io/gorm"
)

// restrictedOwnerUserId 受限家主用户ID（hifastday@hifast.com）
// 该用户本人及其家庭成员只允许返回第一个设备
const restrictedOwnerUserId int64 = 37498

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

// Get Device List
func NewGetDeviceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetDeviceListLogic {
	return &GetDeviceListLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetDeviceListLogic) GetDeviceList() (resp *types.GetDeviceListResponse, err error) {
	userInfo := l.ctx.Value(constant.CtxKeyUser).(*user.User)

	restricted, err := l.isRestrictedScope(userInfo.Id)
	if err != nil {
		return nil, err
	}

	if restricted {
		// 受限逻辑：hifastday@hifast.com (userId=37498) 本人及其家庭成员
		// 只返回当前用户自己的第一个设备，其余丢弃
		// 原始代码（保留以供对照）：
		// scopeHelper := newFamilyScopeHelper(l.ctx, l.svcCtx)
		// scopeUserIds, err := scopeHelper.resolveScopedUserIds(userInfo.Id)
		// if err != nil { return nil, err }
		// list, count, err := l.svcCtx.UserModel.QueryDeviceListByUserIds(l.ctx, scopeUserIds)
		// ...（for 循环为所有设备赋 DeviceNo）
		var ownList []*user.Device
		ownList, _, err = l.svcCtx.UserModel.QueryDeviceList(l.ctx, userInfo.Id)
		if err != nil {
			return nil, err
		}
		userRespList := make([]types.UserDevice, 0, 1)
		if len(ownList) > 0 {
			var item types.UserDevice
			tool.DeepCopy(&item, ownList[0])
			item.DeviceNo = tool.DeviceIdToHash(ownList[0].Id)
			userRespList = append(userRespList, item)
		}
		resp = &types.GetDeviceListResponse{
			Total: int64(len(userRespList)),
			List:  userRespList,
		}
		return
	}

	// 正常逻辑：返回家庭范围内所有成员的设备（含 DeviceNo）
	scopeHelper := newFamilyScopeHelper(l.ctx, l.svcCtx)
	var scopeUserIds []int64
	scopeUserIds, err = scopeHelper.resolveScopedUserIds(userInfo.Id)
	if err != nil {
		return nil, err
	}
	var list []*user.Device
	var count int64
	list, count, err = l.svcCtx.UserModel.QueryDeviceListByUserIds(l.ctx, scopeUserIds)
	if err != nil {
		return nil, err
	}
	userRespList := make([]types.UserDevice, 0, len(list))
	for _, d := range list {
		var item types.UserDevice
		tool.DeepCopy(&item, d)
		item.DeviceNo = tool.DeviceIdToHash(d.Id)
		userRespList = append(userRespList, item)
	}
	resp = &types.GetDeviceListResponse{
		Total: count,
		List:  userRespList,
	}
	return
}

// isRestrictedScope 判断当前用户是否在受限范围内：
//  1. 当前用户本身即 restrictedOwnerUserId（hifastday@hifast.com）
//  2. 当前用户所在家庭的家主是 restrictedOwnerUserId（即通过该邮箱登录的其他设备用户）
func (l *GetDeviceListLogic) isRestrictedScope(currentUserId int64) (bool, error) {
	if currentUserId == restrictedOwnerUserId {
		return true, nil
	}
	var family user.UserFamily
	err := l.svcCtx.DB.WithContext(l.ctx).
		Model(&user.UserFamily{}).
		Joins("JOIN user_family_member ON user_family_member.family_id = user_family.id AND user_family_member.user_id = ? AND user_family_member.status = ?",
			currentUserId, user.FamilyMemberActive).
		Where("user_family.owner_user_id = ? AND user_family.status = ? AND user_family.deleted_at IS NULL",
			restrictedOwnerUserId, user.FamilyStatusActive).
		First(&family).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return false, nil
		}
		return false, err
	}
	return true, nil
}
