<?php

namespace App\Repositories;

use App\Models\Machines;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;

class MachineRepository extends BaseRepository
{
    protected function resolveModel(): Model
    {
        return new Machines();
    }

    /**
     * Get all machines with processes
     */
    public function getWithProcess(): Collection
    {
        return $this->with(['processes'])
            ->orderBy('machine_name', 'asc')
            ->all();
    }

    /**
     * Get machines by process
     */
    public function getByProcess(int $processId): Collection
    {
        return $this->where('process_id', $processId)
            ->orderBy('machine_name', 'asc')
            ->all();
    }

    /**
     * Get active machines
     */
    public function getActive(): Collection
    {
        return $this->where('status', 'active')
            ->orderBy('machine_name', 'asc')
            ->all();
    }

    /**
     * Get available machines (not in use)
     */
    public function getAvailable(): Collection
    {
        return $this->where('status', 'active')
            ->where('is_running', false)
            ->orderBy('machine_name', 'asc')
            ->all();
    }

    /**
     * Get machines by status
     */
    public function getByStatus(string $status): Collection
    {
        return $this->where('status', $status)
            ->orderBy('machine_name', 'asc')
            ->all();
    }

    /**
     * Search machines
     */
    public function search(string $term): Collection
    {
        $query = $this->getQuery();
        $query->where(function ($q) use ($term) {
            $q->where('machine_name', 'like', "%{$term}%")
                ->orWhere('machine_code', 'like', "%{$term}%");
        });
        $result = $query->get();
        $this->resetQuery();
        return $result;
    }
}
