<?php

namespace App\Http\Controllers;

use App\Enums\UserRole;
use App\Models\Printer;
use App\Models\Reading;
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ReadingController extends Controller
{
    public function create(Printer $printer): View
    {
        return view('readings.create', [
            'printer' => $printer,
            'technicians' => $this->technicians(),
        ]);
    }

    public function store(Request $request, Printer $printer): RedirectResponse
    {
        $printer->readings()->create($this->validated($request));

        return redirect()->route('printers.show', $printer)->with('success', 'Читањето е зачувано.');
    }

    public function edit(Reading $reading): View
    {
        return view('readings.edit', [
            'reading' => $reading,
            'printer' => $reading->printer,
            'technicians' => $this->technicians(),
        ]);
    }

    public function update(Request $request, Reading $reading): RedirectResponse
    {
        $reading->update($this->validated($request));

        return redirect()->route('printers.show', $reading->printer)->with('success', 'Читањето е зачувано.');
    }

    public function destroy(Reading $reading): RedirectResponse
    {
        $printer = $reading->printer;
        $reading->delete();

        return redirect()->route('printers.show', $printer)->with('success', 'Читањето е избришано.');
    }

    private function technicians(): Collection
    {
        return User::where('role', UserRole::Technician->value)->orderBy('name')->get();
    }

    private function validated(Request $request): array
    {
        return $request->validate([
            'reading_date' => ['required', 'date'],
            'bw_counter' => ['nullable', 'integer', 'min:0'],
            'color_counter' => ['nullable', 'integer', 'min:0'],
            'scan_counter' => ['nullable', 'integer', 'min:0'],
            'technician_id' => ['nullable', 'exists:users,id'],
            'toner_black' => ['nullable', 'integer', 'between:1,5'],
            'toner_cyan' => ['nullable', 'integer', 'between:1,5'],
            'toner_magenta' => ['nullable', 'integer', 'between:1,5'],
            'toner_yellow' => ['nullable', 'integer', 'between:1,5'],
            'description' => ['nullable', 'string'],
        ]);
    }
}
