package user

import (
	"context"
	"time"

	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 DissolveFamilyLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logger.Logger
}

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

func (l *DissolveFamilyLogic) DissolveFamily(req *types.DissolveFamilyRequest) 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")
	}
	if family.Status != modelUser.FamilyStatusActive {
		return errors.Wrapf(xerr.NewErrCode(xerr.FamilyStatusInvalid), "family status is invalid")
	}

	now := time.Now()
	transactionErr := l.svcCtx.DB.WithContext(l.ctx).Transaction(func(tx *gorm.DB) error {
		if err = tx.Model(&modelUser.UserFamilyMember{}).
			Where("family_id = ? AND deleted_at IS NULL AND status = ?", req.FamilyId, modelUser.FamilyMemberActive).
			Updates(map[string]interface{}{
				"status":  modelUser.FamilyMemberRemoved,
				"left_at": now,
			}).Error; err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "remove family members failed")
		}

		if err = tx.Model(&modelUser.UserFamily{}).
			Where("id = ?", req.FamilyId).
			Update("status", 0).Error; err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "disable family failed")
		}
		return nil
	})
	if transactionErr != nil {
		return transactionErr
	}

	return nil
}
