<?php

namespace Kylin\LawCase\Policies;

use App\Models\User;
use Kylin\LawCase\Models\Client;

/**
 * 客户权限策略
 */
class ClientPolicy
{
    /**
     * 查看客户 - 管理员/合伙人可查看所有，其他仅可查看关联案件的客户
     */
    public function view(User $user, Client $client): bool
    {
        if ($user->hasRole('super_admin') || $user->hasRole('partner')) {
            return true;
        }

        // 财务和行政可查看所有客户
        if ($user->hasRole('finance') || $user->hasRole('admin')) {
            return true;
        }

        // 律师/助理：仅可查看自己参与案件的客户
        return $client->cases()
            ->where(function ($q) use ($user) {
                $q->where('principal_lawyer_id', $user->id)
                  ->orWhere('assistant_lawyer_id', $user->id)
                  ->orWhereHas('lawyers', fn($q2) => $q2->where('user_id', $user->id));
            })
            ->exists();
    }

    public function delete(User $user, Client $client): bool
    {
        return $user->hasRole('super_admin');
    }
}
