package user

import (
	"context"
	"errors"

	"github.com/rede5/gohorsejobs/backend/internal/core/domain/entity"
	"github.com/rede5/gohorsejobs/backend/internal/core/ports"
)

type UpdatePasswordUseCase struct {
	userRepo    ports.UserRepository
	authService ports.AuthService
}

func NewUpdatePasswordUseCase(userRepo ports.UserRepository, authService ports.AuthService) *UpdatePasswordUseCase {
	return &UpdatePasswordUseCase{
		userRepo:    userRepo,
		authService: authService,
	}
}

func (uc *UpdatePasswordUseCase) Execute(ctx context.Context, userID, currentPassword, newPassword string) error {
	if newPassword == "" {
		return errors.New("new password is required")
	}
	if len(newPassword) < 8 {
		return errors.New("new password must be at least 8 characters")
	}

	user, err := uc.userRepo.FindByID(ctx, userID)
	if err != nil {
		return err
	}
	if user == nil {
		return errors.New("user not found")
	}

	if !uc.authService.VerifyPassword(user.PasswordHash, currentPassword) {
		return errors.New("current password is invalid")
	}

	hashed, err := uc.authService.HashPassword(newPassword)
	if err != nil {
		return err
	}

	user.PasswordHash = hashed
	if user.Status == entity.UserStatusForceChangePassword {
		user.Status = entity.UserStatusActive
	}

	_, err = uc.userRepo.Update(ctx, user)
	return err
}
