<?php

namespace App\Policies;

use App\Models\Message;
use App\Models\User;

class MessagePolicy
{
    public function viewAny(User $user): bool
    {
        return $user !== null;
    }

    public function view(User $user, Message $message): bool
    {
        return $this->owns($user, $message) || $this->isAdmin($user);
    }

    public function create(User $user): bool
    {
        return $user !== null;
    }

    public function update(User $user, Message $message): bool
    {
        return $this->owns($user, $message) || $this->isAdmin($user);
    }

    public function delete(User $user, Message $message): bool
    {
        return $this->owns($user, $message) || $this->isAdmin($user);
    }

    private function owns(User $user, Message $message): bool
    {
        return $message->sender_id === $user->id || $message->recipient_id === $user->id;
    }

    private function isAdmin(User $user): bool
    {
        $roles = $user->roles()
            ->pluck('roles.name')
            ->map(fn ($name) => strtolower((string) $name))
            ->toArray();

        foreach (['administrator', 'admin', 'principal', 'vice_principal', 'vice-principal'] as $role) {
            if (in_array($role, $roles, true)) {
                return true;
            }
        }

        return false;
    }
}
