<?php

namespace App\Models;

use CodeIgniter\Model;

class MaintenanceEventModel extends Model
{
    protected $table         = 'maintenance_events';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $allowedFields = [
        'maintenance_intervention_id',
        'event_type',
        'event_message',
        'event_data',
        'happened_at',
        'created_by_user_id',
    ];

    public function withCreator()
    {
        return $this->select('maintenance_events.*, users.name AS created_by_name')
            ->join('users', 'users.id = maintenance_events.created_by_user_id', 'left');
    }

    public function forIntervention(int $interventionId): array
    {
        return $this->withCreator()
            ->where('maintenance_events.maintenance_intervention_id', $interventionId)
            ->orderBy('maintenance_events.happened_at', 'DESC')
            ->findAll();
    }
}
