<?php

namespace App\Models;

use App\Enums\PrinterStatus;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

class Printer extends Model
{
    use HasFactory;

    protected $fillable = [
        'client_id', 'manufacturer', 'model', 'serial_number', 'installation_date',
        'status', 'notes',
    ];

    protected function casts(): array
    {
        return [
            'status' => PrinterStatus::class,
            'installation_date' => 'date',
        ];
    }

    protected static function booted(): void
    {
        static::creating(function (Printer $printer) {
            if (empty($printer->qr_token)) {
                $printer->qr_token = (string) Str::uuid();
            }
        });
    }

    public function client(): BelongsTo
    {
        return $this->belongsTo(Client::class);
    }

    public function readings(): HasMany
    {
        // Reserved for Phase 3b (readings table). Safe to define now.
        return $this->hasMany(Reading::class);
    }

    public function readingLog(): Collection
    {
        $readings = $this->readings()->with('technician')->orderBy('reading_date')->orderBy('id')->get();

        $last = ['bw' => null, 'color' => null, 'scan' => null];

        return $readings->map(function (Reading $reading) use (&$last) {
            $row = ['reading' => $reading];

            foreach (['bw', 'color', 'scan'] as $k) {
                $value = $reading->{$k.'_counter'};

                if ($value === null) {
                    $row[$k.'_used'] = null;
                    continue;
                }

                $row[$k.'_used'] = $last[$k] === null ? null : $value - $last[$k];
                $last[$k] = $value;
            }

            return $row;
        });
    }
}
