<?php

namespace App\Services;

use App\Repositories\Contracts\RepositoryInterface;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/**
 * Base application service.
 *
 * Services own business rules and transactions; they delegate persistence to
 * repositories. Controllers talk only to services, never to repositories.
 */
abstract class BaseService
{
    public function __construct(protected RepositoryInterface $repository)
    {
    }

    public function paginate(int $perPage = 15)
    {
        return $this->repository->paginate($perPage);
    }

    public function find(int|string $id): ?Model
    {
        return $this->repository->find($id);
    }

    public function findOrFail(int|string $id): Model
    {
        return $this->repository->findOrFail($id);
    }

    public function create(array $data): Model
    {
        return DB::transaction(fn () => $this->repository->create($data));
    }

    public function update(int|string $id, array $data): Model
    {
        return DB::transaction(fn () => $this->repository->update($id, $data));
    }

    public function delete(int|string $id): bool
    {
        return DB::transaction(fn () => $this->repository->delete($id));
    }
}
