<?php

namespace Kylin\LawCase\Repositories;

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

/**
 * 案件仓储
 *
 * 封装案件数据查询逻辑。
 */
class CaseRepository
{
    public function paginate(array $filters = [], int $perPage = 15): LengthAwarePaginator
    {
        $query = CaseModel::with(['principalLawyer', 'assistantLawyer', 'client']);

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

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

        if (!empty($filters['lawyer_id'])) {
            $query->where(function ($q) use ($filters) {
                $q->where('principal_lawyer_id', $filters['lawyer_id'])
                  ->orWhere('assistant_lawyer_id', $filters['lawyer_id']);
            });
        }

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

        if (!empty($filters['data_scope_user_id'])) {
            $userId = $filters['data_scope_user_id'];
            $query->where(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): CaseModel
    {
        return CaseModel::with([
            'principalLawyer',
            'assistantLawyer',
            'client',
            'milestones',
            'documents',
            'fees',
            'schedules',
        ])->findOrFail($id);
    }

    public function update(CaseModel $case, array $data): CaseModel
    {
        $case->update($data);
        return $case->fresh();
    }
}
