<?php

namespace Network;

use Model\Notification;
use Model\RelationshipRequest;
use Model\User;
use Repository\IUserRepository;
use Stub\RelationshipRequestRepository;

class RelationshipService implements IFriendRequestService
{
    private RelationshipRequestRepository $relationshipRequestRepository;
    private INotificationService $notificationService;

    /**
     * @param RelationshipRequestRepository $relationshipRequestRepository
     */
    public function __construct(RelationshipRequestRepository $relationshipRequestRepository,INotificationService $notificationService)
    {
        $this->relationshipRequestRepository = $relationshipRequestRepository;
        $this->notificationService = $notificationService;
    }


    public function sendRequest(User $fromUser, User $toUser): bool
    {
        try {
            $friendRequest = new RelationshipRequest(random_int(1,150), $fromUser->getId(), $toUser->getId());

        } catch (\Exception $e) {
            return false;
        }
        $friendRequest->attachObserver($this->notificationService);
        $friendRequest->updateStatus( 'pending');

        $this->relationshipRequestRepository->addItem($friendRequest);

        $toUser->getRole()->addUsersRequests($friendRequest);
        return true;
    }


    public function acceptRequest(RelationshipRequest $request): bool
    {
        // Mark the request as accepted
        $request->updateStatus('accepted');
        $request->detachObserver($this->notificationService);
        $this->relationshipRequestRepository->deleteItem($request);
        return true;
    }

    public function declineRequest(RelationshipRequest $request): bool
    {
        $request->updateStatus('declined') ;
        $request->detachObserver($this->notificationService);
        $this->relationshipRequestRepository->deleteItem($request);
        return true;
    }
}