<?php

namespace Kylin\LawCase\Repositories;

use Kylin\LawCase\Models\Client;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

/**
 * 客户仓储
 *
 * 封装客户数据查询逻辑。
 */
class ClientRepository
{
    public function paginate(array $filters = [], int $perPage = 15): LengthAwarePaginator
    {
        $query = Client::query();

        if (!empty($filters['keyword'])) {
            $query->where(function ($q) use ($filters) {
                $q->where('client_name', 'like', "%{$filters['keyword']}%")
                  ->orWhere('client_no', 'like', "%{$filters['keyword']}%");
            });
        }

        if (!empty($filters['client_type'])) {
            $query->where('client_type', $filters['client_type']);
        }

        // 数据范围过滤：非管理员只能看自己参与案件的客户
        if (!empty($filters['data_scope_user_id'])) {
            $userId = $filters['data_scope_user_id'];
            $query->whereHas('cases', function ($q) use ($userId) {
                $q->where('principal_lawyer_id', $userId)
                  ->orWhere('assistant_lawyer_id', $userId)
                  ->orWhereHas('lawyers', fn($q2) => $q2->where('user_id', $userId));
            });
        }

        return $query->orderByDesc('created_at')->paginate($perPage);
    }

    public function find(int $id): Client
    {
        return Client::with(['cases', 'fees', 'conflictChecks'])->findOrFail($id);
    }
}
