<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PrinterJob extends Model
{
    use HasFactory;

    protected $fillable = [
        'printer_id',
        'job_type',
        'job_status',
        'content',
        'priority',
        'attempts',
        'error_message',
        'metadata',
        'processed_at',
        'completed_at',
    ];

    protected $casts = [
        'content' => 'array',
        'metadata' => 'array',
        'processed_at' => 'datetime',
        'completed_at' => 'datetime',
    ];

    protected $appends = [
        'processing_time',
        'is_urgent',
        'job_type_icon',
    ];

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

    public function getProcessingTimeAttribute(): ?int
    {
        if (!$this->processed_at || !$this->completed_at) {
            return null;
        }
        
        return $this->processed_at->diffInSeconds($this->completed_at);
    }

    public function getIsUrgentAttribute(): bool
    {
        return $this->priority <= 3;
    }

    public function getJobTypeIconAttribute(): string
    {
        switch ($this->job_type) {
            case 'receipt':
                return '🧾';
            case 'label':
                return '🏷️';
            case 'report':
                return '📊';
            case 'test':
                return '🧪';
            default:
                return '📄';
        }
    }

    public function scopePending($query)
    {
        return $query->where('job_status', 'pending');
    }

    public function scopeProcessing($query)
    {
        return $query->where('job_status', 'processing');
    }

    public function scopeCompleted($query)
    {
        return $query->where('job_status', 'completed');
    }

    public function scopeFailed($query)
    {
        return $query->where('job_status', 'failed');
    }

    public function scopeByType($query, $type)
    {
        return $query->where('job_type', $type);
    }

    public function scopeHighPriority($query)
    {
        return $query->where('priority', '<=', 3);
    }

    public function scopeRecent($query, $hours = 24)
    {
        return $query->where('created_at', '>=', now()->subHours($hours));
    }
}