<?php

namespace App\PackagesApi\v4\Controllers\User;

use App\Http\Controllers\Controller;
use App\Packages\User\Models\User;
use App\Packages\User\Models\UserNotification;
use App\Packages\v4\User\Repository\UserNotificationRepository;
use App\Packages\v4\User\Transformer\NotificationTransformer;
use App\PackagesApi\v4\Requests\Auth\PushTokenRequest;
use App\PackagesApi\v4\Requests\Notification\NotificationRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Class NotificationController
 *
 * @package App\Http\Controllers\API
 */
class NotificationController extends Controller
{
    /** @var User */
    private $user;

    public function __construct()
    {
        $this->user = user();
    }

    /**
     * @return JsonResponse
     */
    public function getList(Request $request)
    {
        $this->user->saveAccess('View notifications list');

        $lastSeen = request()->get('last_seen', null);
        $page = (int) request()->get('page', 1);

        $totalCount = UserNotificationRepository::init()->userNotificationsCount($this->user);
        $notifications = UserNotificationRepository::init()->getListPaginated($this->user, $lastSeen, $page);
        $notifications = $notifications->map(function ($notification) {
            return NotificationTransformer::smallObject($notification);
        });

        $this->user->updateNotificationSeen();

        return jsonSuccess([
            'total_count' => $totalCount,
            'current_page' => $page,
            'last_page' => max((int) ceil($totalCount /  UserNotificationRepository::LIMIT_PAGE), 1),
            'notifications' => $notifications,
        ]);
    }

    /**
     * @TODO:
     *
     * @param NotificationRequest $request
     *
     * @return JsonResponse
     */
    public function isSeen(NotificationRequest $request)
    {
        $notification = UserNotificationRepository::init()->firstById($request->notification_id);
        if (!$notification) {
            return jsonErrorEntity(['message' => 'Notification does not exists']);
        }

        if ($notification->is_seen) {
            return jsonErrorEntity(['message' => 'Notification is already seen']);
        }

        $notification->is_seen = true;
        $notification->save();

        return jsonSuccess();
    }

    /**
     * @param PushTokenRequest $request
     *
     * @return JsonResponse
     */
    public function registerPushToken(PushTokenRequest $request)
    {
        $this->user->ios_push_token = $request->token;
        $this->user->save();

        return jsonSuccess();
    }

    /**
     * @return JsonResponse
     */
    public function unRegisterPushToken()
    {
        $this->user->ios_push_token = null;
        $this->user->save();

        return jsonSuccess();
    }
}
