<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * A physical checkout station (till / workstation) inside a store. Each
 * terminal carries its own hardware configuration — receipt printer,
 * label printer, cash drawer, barcode scanner — stored as JSON on
 * `default_printer_config` / `label_printer_config`.
 *
 * H1 (this slice) ships the terminal entity + management CRUD + the
 * picker helpers ({@see current_terminal()}). The hardware-config
 * wizard that populates the JSON columns lands with the print-bridge
 * slice (docs/features/hardware.md §4).
 */
class Terminal extends Model
{
    protected $fillable = [
        'store_id',
        'code',
        'name',
        'default_printer_config',
        'label_printer_config',
        'last_seen_at',
        'is_active',
    ];

    protected function casts(): array
    {
        return [
            'default_printer_config' => 'array',
            'label_printer_config'   => 'array',
            'last_seen_at'           => 'datetime',
            'is_active'              => 'boolean',
        ];
    }

    /** @return BelongsTo<Store, $this> */
    public function store(): BelongsTo
    {
        return $this->belongsTo(Store::class);
    }

    /** @param Builder<Terminal> $q */
    public function scopeActive(Builder $q): void
    {
        $q->where('is_active', true);
    }

    /** @param Builder<Terminal> $q */
    public function scopeForStore(Builder $q, int $storeId): void
    {
        $q->where('store_id', $storeId);
    }

    /** Newest first across every admin list / export. */
    public function scopeOrdered(Builder $q): void
    {
        $q->orderByDesc('id');
    }
}
