<?php

namespace App\Services;

use App\Models\Equipment\Equipment;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class EquipmentService
{
    public function getEquipments(array $filters = [], int $perPage = 20): LengthAwarePaginator
    {
        $query = Equipment::query()->with('manager');

        if (! empty($filters['search'])) {
            $search = $filters['search'];
            $query->where(function ($q) use ($search) {
                $q->where('equipment_code', 'like', "%{$search}%")
                    ->orWhere('name', 'like', "%{$search}%");
            });
        }

        if (! empty($filters['status'])) {
            $query->where('status', $filters['status']);
        }

        if (! empty($filters['production_line'])) {
            $query->where('production_line', $filters['production_line']);
        }

        if (! empty($filters['equipment_type'])) {
            $query->where('equipment_type', $filters['equipment_type']);
        }

        $sortBy = $filters['sort_by'] ?? 'sort_order';
        $sortDir = $filters['sort_direction'] ?? 'asc';
        $query->orderBy($sortBy, $sortDir);

        return $query->paginate($perPage);
    }

    public function getEquipmentById(int $id): ?Equipment
    {
        return Equipment::with(['manager', 'inspectionTemplates', 'repairs', 'processes', 'photos'])->find($id);
    }

    public function createEquipment(array $data): Equipment
    {
        $data['tenant_id'] = session('selected_tenant_id', 1);
        $data['created_by'] = auth()->id();

        return Equipment::create($data);
    }

    public function updateEquipment(int $id, array $data): Equipment
    {
        $equipment = Equipment::findOrFail($id);
        $data['updated_by'] = auth()->id();
        $equipment->update($data);

        return $equipment->fresh();
    }

    public function deleteEquipment(int $id): bool
    {
        $equipment = Equipment::findOrFail($id);
        $equipment->deleted_by = auth()->id();
        $equipment->save();

        return $equipment->delete();
    }

    public function restoreEquipment(int $id): bool
    {
        $equipment = Equipment::onlyTrashed()->findOrFail($id);

        return $equipment->restore();
    }

    public function getDashboardStats(): array
    {
        $total = Equipment::count();
        $active = Equipment::where('status', 'active')->count();
        $idle = Equipment::where('status', 'idle')->count();
        $disposed = Equipment::where('status', 'disposed')->count();

        return compact('total', 'active', 'idle', 'disposed');
    }

    public function getTypeStats(): array
    {
        return Equipment::where('status', '!=', 'disposed')
            ->selectRaw('equipment_type, count(*) as count')
            ->groupBy('equipment_type')
            ->pluck('count', 'equipment_type')
            ->toArray();
    }

    public function getEquipmentList(): \Illuminate\Database\Eloquent\Collection
    {
        return Equipment::where('is_active', true)
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get(['id', 'equipment_code', 'name', 'equipment_type', 'production_line']);
    }
}
