<?php

namespace App\Models;

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

class AttendanceEvent extends Model
{
    use HasFactory;

    protected $fillable = [
        'event_uuid', 'employee_id', 'device_id', 'site_id', 'direction', 'ts',
        'confidence', 'liveness_pass', 'source', 'operator', 'direction_confidence',
        'corrected_by', 'corrects_event_id', 'snapshot_path',
    ];

    protected function casts(): array
    {
        return [
            'ts' => 'datetime',
            'confidence' => 'float',
            'liveness_pass' => 'boolean',
            'direction_confidence' => 'float',
        ];
    }

    public function employee()
    {
        return $this->belongsTo(Employee::class);
    }

    public function device()
    {
        return $this->belongsTo(Device::class);
    }

    public function site()
    {
        return $this->belongsTo(Site::class);
    }

    /** The newer event that corrected this one (if any). */
    public function correction()
    {
        return $this->belongsTo(AttendanceEvent::class, 'corrected_by');
    }

    /** The older event this one corrects (if any). */
    public function corrects()
    {
        return $this->belongsTo(AttendanceEvent::class, 'corrects_event_id');
    }

    public function isCorrected(): bool
    {
        return $this->corrected_by !== null;
    }

    public function scopeNotCorrected($query)
    {
        return $query->whereNull('corrected_by');
    }
}
