<?php

namespace Kylin\LawCase\Repositories;

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

/**
 * 日程仓储
 *
 * 封装日程数据查询逻辑。
 */
class ScheduleRepository
{
    public function paginate(array $filters = [], int $perPage = 15): LengthAwarePaginator
    {
        $query = Schedule::with(['case', 'user']);

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

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

        if (!empty($filters['start_date']) && !empty($filters['end_date'])) {
            $query->byDateRange($filters['start_date'], $filters['end_date']);
        }

        // 数据范围过滤：非管理员只能看自己的日程
        if (!empty($filters['data_scope_user_id'])) {
            $userId = $filters['data_scope_user_id'];
            $query->where('user_id', $userId);
        }

        return $query->orderBy('start_time')->paginate($perPage);
    }

    public function find(int $id): Schedule
    {
        return Schedule::with(['case', 'user'])->findOrFail($id);
    }
}
