<?php

namespace App\Services\MasterData;

use App\Services\BaseService;
use App\Repositories\ProcessRepository;
use App\Models\Process;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class ProcessService extends BaseService
{
    protected ProcessRepository $processRepository;

    public function __construct(ProcessRepository $repository)
    {
        parent::__construct($repository);
        $this->processRepository = $repository;
    }

    /**
     * Get with conversion type
     */
    public function getAllWithConversionType(): Collection
    {
        return $this->processRepository->getWithConversionType();
    }

    /**
     * Get by conversion type
     */
    public function getByConversionType(int $typeId): Collection
    {
        return $this->processRepository->getByConversionType($typeId);
    }

    /**
     * Get active processes
     */
    public function getActive(): Collection
    {
        return $this->processRepository->getActive();
    }

    /**
     * Get with machines
     */
    public function getAllWithMachines(): Collection
    {
        return $this->processRepository->getWithMachines();
    }

    /**
     * Search processes
     */
    public function search(string $term): Collection
    {
        return $this->processRepository->search($term);
    }

    /**
     * Assign machines to process
     */
    public function assignMachines(int $processId, array $machineIds): Process
    {
        return DB::transaction(function () use ($processId, $machineIds) {
            $process = $this->findByIdOrFail($processId);

            // Sync machines
            $process->machines()->sync($machineIds);

            $this->logAction('Machines assigned to process', [
                'process_id' => $processId,
                'machine_count' => count($machineIds),
            ]);

            return $process->fresh(['machines']);
        });
    }

    /**
     * Assign operators to process
     */
    public function assignOperators(int $processId, array $operatorIds): Process
    {
        return DB::transaction(function () use ($processId, $operatorIds) {
            $process = $this->findByIdOrFail($processId);

            // Sync operators
            $process->operators()->sync($operatorIds);

            $this->logAction('Operators assigned to process', [
                'process_id' => $processId,
                'operator_count' => count($operatorIds),
            ]);

            return $process->fresh(['operators']);
        });
    }
}
