package user

import (
	"context"

	modelUser "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/xerr"
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

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

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

func (l *UpdateFamilyMaxMembersLogic) UpdateFamilyMaxMembers(req *types.UpdateFamilyMaxMembersRequest) error {
	var family modelUser.UserFamily
	err := l.svcCtx.DB.WithContext(l.ctx).
		Where("id = ? AND deleted_at IS NULL", req.FamilyId).
		First(&family).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.Wrapf(xerr.NewErrCode(xerr.FamilyNotExist), "family does not exist")
		}
		return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query family failed")
	}

	var activeCount int64
	if err = l.svcCtx.DB.WithContext(l.ctx).
		Table("user_family_member").
		Where("family_id = ? AND deleted_at IS NULL AND status = ?", req.FamilyId, modelUser.FamilyMemberActive).
		Count(&activeCount).Error; err != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "count active members failed")
	}
	if req.MaxMembers < activeCount {
		return errors.Wrapf(xerr.NewErrCode(xerr.FamilyMemberLimitExceeded), "max members below active member count")
	}

	if err = l.svcCtx.DB.WithContext(l.ctx).
		Model(&modelUser.UserFamily{}).
		Where("id = ?", req.FamilyId).
		Update("max_members", req.MaxMembers).Error; err != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "update family max members failed")
	}

	return nil
}
