<?php

namespace App\Repositories\Eloquent;

use App\Repositories\Contracts\BaseRepositoryInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;

/**
 * @template T of Model
 *
 * @implements BaseRepositoryInterface<T>
 */
abstract class BaseRepository implements BaseRepositoryInterface
{
    /**
     * @param  T  $model
     */
    public function __construct(protected Model $model) {}

    /**
     * @param  array<string, mixed>  $filters
     * @return LengthAwarePaginator<int, T>
     */
    public function paginate(array $filters = [], int $perPage = 15): LengthAwarePaginator
    {
        return $this->model->newQuery()->latest()->paginate($perPage);
    }

    /**
     * @return T|null
     */
    public function findById(int $id): ?Model
    {
        return $this->model->newQuery()->find($id);
    }

    /**
     * @param  array<string, mixed>  $data
     * @return T
     */
    public function create(array $data): Model
    {
        return $this->model->newQuery()->create($data);
    }

    /**
     * @param  array<string, mixed>  $data
     * @return T
     */
    public function update(Model $model, array $data): Model
    {
        $model->update($data);

        return $model->fresh();
    }

    public function delete(Model $model): bool
    {
        return $model->delete();
    }
}
