<?php

namespace App\Services;

use App\Models\ImprovementType;
use Illuminate\Database\Eloquent\Collection;

class ImprovementTypeService
{
    public function getAll(string $origin): Collection
    {
        $improvement_types = ImprovementType::query()
            ->orderBy('created_at', 'desc')
            ->when($origin, function ($query) use ($origin) {
                $query->when($origin === 'both', function ($query) {
                    $query->whereIn('improvement_type', ['client', 'provider', 'both']);
                })
                    ->when($origin !== 'both', function ($query) use ($origin) {
                        $query->whereIn('improvement_type', [$origin, 'both']);
                    });
            })
            ->get();

        return $improvement_types;
    }

    public function findById(int $id): ?ImprovementType
    {
        return ImprovementType::find($id);
    }

    public function create(array $data): ImprovementType
    {
        return ImprovementType::create($data);
    }

    public function update(int $id, array $data): ?ImprovementType
    {
        $model = $this->findById($id);

        if (! $model) {
            return null;
        }

        $model->update($data);

        return $model->fresh();
    }

    public function delete(int $id): bool
    {
        $model = $this->findById($id);

        if (! $model) {
            return false;
        }

        return $model->delete();
    }
}
