<?php

namespace Kylin\LawCase\Policies;

use App\Models\User;
use Kylin\LawCase\Models\Document;
use Kylin\LawCase\Enums\AccessLevel;

/**
 * 文档权限策略
 */
class DocumentPolicy
{
    public function view(User $user, Document $document): bool
    {
        if ($user->hasRole('super_admin') || $user->hasRole('partner')) {
            return true;
        }

        if ($document->uploaded_by === $user->id) {
            return true;
        }

        $accessLevel = $document->access_level instanceof AccessLevel
            ? $document->access_level
            : AccessLevel::tryFrom($document->access_level);

        return match ($accessLevel) {
            AccessLevel::PUBLIC => true,
            AccessLevel::CASE_MEMBERS => $document->case
                && ($document->case->principal_lawyer_id === $user->id
                    || $document->case->assistant_lawyer_id === $user->id
                    || $document->case->lawyers()->where('user_id', $user->id)->exists()),
            AccessLevel::PRINCIPAL_LAWYER => $document->case
                && $document->case->principal_lawyer_id === $user->id,
            AccessLevel::OWNER_ONLY => $document->uploaded_by === $user->id,
            default => false,
        };
    }

    public function delete(User $user, Document $document): bool
    {
        return $user->hasRole('super_admin') || $document->uploaded_by === $user->id;
    }
}
