<?php

namespace App\Services;

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

class EquipmentRepairService
{
    public function getRepairs(array $filters = [], int $perPage = 20): LengthAwarePaginator
    {
        $query = EquipmentRepair::query()->with('equipment', 'repairer');

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

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

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

        if (! empty($filters['date_to'])) {
            $query->where('repair_date', '<=', $filters['date_to']);
        }

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

        return $query->orderBy('repair_date', 'desc')->paginate($perPage);
    }

    public function getRepairById(int $id): ?EquipmentRepair
    {
        return EquipmentRepair::with('equipment', 'repairer')->find($id);
    }

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

        return EquipmentRepair::create($data);
    }

    public function updateRepair(int $id, array $data): EquipmentRepair
    {
        $repair = EquipmentRepair::findOrFail($id);
        $data['updated_by'] = auth()->id();
        $repair->update($data);

        return $repair->fresh();
    }

    public function deleteRepair(int $id): bool
    {
        $repair = EquipmentRepair::findOrFail($id);

        return $repair->delete();
    }

    public function getRecentRepairs(int $limit = 5): \Illuminate\Database\Eloquent\Collection
    {
        return EquipmentRepair::with('equipment')
            ->orderBy('repair_date', 'desc')
            ->limit($limit)
            ->get();
    }
}
