<?php

namespace Velis\Policy\Bpm\Ticket;

use Velis\App;
use Velis\App\User;
use Velis\Bpm\Ticket\Post;

class PostPolicy
{
    private Post $post;

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

    public function canAccess(User $user): bool
    {
        switch ($this->post->ticket_post_visibility_id) {
            case Post::TYPE_PUBLIC:
                return self::canSeePublicPost($user);
            case Post::TYPE_PROTECTED:
                return self::canSeeInternalPost($user);
            case Post::TYPE_PRIVATE:
                return self::canSeePrivatePost($user, $this->post->getAuthor()->id());
        }

        return false;
    }

    public static function canSeePublicPost(User $user): bool
    {
        return true;
    }

    public static function canEditPublicPost(User $user): bool
    {
        return !$user->isExternalService()
            || App::settings('PublicNotesForExternalServices');
    }

    public static function canSeeInternalPost(User $user): bool
    {
        return $user->hasPriv('Ticket', 'InternalPostsAccess');
    }

    public static function canSeePrivatePost(User $user, ?int $authorId = null): bool
    {
        return $user->id() == $authorId
            || $user->hasPriv('Ticket', 'PrivatePostsAccess');
    }
}
