<?php

namespace App\Models;

use CodeIgniter\Model;

class MaintenanceFileModel extends Model
{
    protected $table         = 'maintenance_files';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $allowedFields = [
        'maintenance_intervention_id',
        'maintenance_intervention_task_id',
        'uploaded_by_user_id',
        'file_category',
        'original_name',
        'stored_name',
        'storage_path',
        'mime_type',
        'file_size_bytes',
        'checksum_sha256',
        'description',
    ];

    public function withRelations()
    {
        return $this->select(
            'maintenance_files.*, users.name AS uploaded_by_name,' .
            ' maintenance_intervention_tasks.sequence_no AS intervention_task_sequence'
        )
            ->join('users', 'users.id = maintenance_files.uploaded_by_user_id', 'left')
            ->join(
                'maintenance_intervention_tasks',
                'maintenance_intervention_tasks.id = maintenance_files.maintenance_intervention_task_id',
                'left'
            );
    }

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