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

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

func (l *RemoveFamilyMemberLogic) RemoveFamilyMember(req *types.RemoveFamilyMemberRequest) 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")
	}

	var member modelUser.UserFamilyMember
	err = l.svcCtx.DB.WithContext(l.ctx).
		Where("family_id = ? AND user_id = ? AND deleted_at IS NULL AND status = ?", req.FamilyId, req.UserId, modelUser.FamilyMemberActive).
		First(&member).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.Wrapf(xerr.NewErrCode(xerr.FamilyNotExist), "active family member does not exist")
		}
		return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query family member failed")
	}
	if member.Role == modelUser.FamilyRoleOwner {
		return errors.Wrapf(xerr.NewErrCode(xerr.FamilyOwnerOperationForbidden), "cannot remove family owner")
	}

	now := time.Now()
	if err = l.svcCtx.DB.WithContext(l.ctx).
		Model(&modelUser.UserFamilyMember{}).
		Where("id = ?", member.Id).
		Updates(map[string]interface{}{
			"status":  modelUser.FamilyMemberRemoved,
			"left_at": now,
		}).Error; err != nil {
		return errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "remove family member failed")
	}

	return nil
}
