<?php

namespace Kylin\LawCase\Repositories;

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

/**
 * 费用仓储
 *
 * 封装费用数据查询逻辑。
 */
class FeeRepository
{
    public function paginate(array $filters = [], int $perPage = 15): LengthAwarePaginator
    {
        $query = Fee::with(['case', 'client', 'approver']);

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

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

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

        // 数据范围过滤：非管理员只能看自己参与案件的费用
        if (!empty($filters['data_scope_user_id'])) {
            $userId = $filters['data_scope_user_id'];
            $query->whereHas('case', 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): Fee
    {
        return Fee::with(['case', 'client', 'approver', 'timeEntries', 'invoices'])->findOrFail($id);
    }
}
