<?php

namespace App\Livewire\Works;

use App\Enums\WorkInternalStatus;
use App\Models\Work;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Contracts\View\View;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithPagination;

#[Layout('layouts.app', ['title' => 'Asignaciones', 'header' => 'Mis asignaciones'])]
#[Title('Asignaciones')]
class TechnicianAssignmentsIndex extends Component
{
    use WithPagination;

    public string $search = '';

    public int $perPage = 15;

    /** @return LengthAwarePaginator<int, Work> */
    #[Computed]
    public function works(): LengthAwarePaginator
    {
        $userId = (int) auth()->id();

        return Work::query()
            ->where('technician_id', $userId)
            ->with([
                'site:id,code,name,project_id',
                'site.project:id,name,color',
                'workType:id,name',
            ])
            ->when($this->search !== '', fn ($q) => $q->where('ot', 'like', '%'.$this->search.'%'))
            ->orderByRaw('CASE WHEN internal_status = ? THEN 1 ELSE 0 END', [WorkInternalStatus::FINALIZADO->value])
            ->orderByDesc('scale_datetime')
            ->paginate($this->perPage);
    }

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedPerPage(): void
    {
        $this->resetPage();
    }

    public function render(): View
    {
        return view('livewire.works.assignments-index');
    }
}
