<?php

namespace App\Models;

use CodeIgniter\Model;

class MaintenanceInterventionModel extends Model
{
    protected $table         = 'maintenance_interventions';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = true;
    protected $allowedFields = [
        'organization_id',
        'site_id',
        'turbine_id',
        'intervention_code',
        'title',
        'description',
        'intervention_type',
        'maintenance_mode',
        'priority',
        'status',
        'reported_at',
        'scheduled_start_at',
        'scheduled_end_at',
        'started_at',
        'completed_at',
        'created_by_user_id',
        'assigned_to_user_id',
        'external_reference',
    ];

    public function withRelations()
    {
        return $this->select(
            'maintenance_interventions.*, organizations.name AS organization_name,' .
            ' sites.name AS site_name, sites.site_code, turbines.turbine_code, turbines.name AS turbine_name,' .
            ' creator.name AS created_by_name, assignee.name AS assigned_to_name'
        )
            ->join('organizations', 'organizations.id = maintenance_interventions.organization_id')
            ->join('sites', 'sites.id = maintenance_interventions.site_id')
            ->join('turbines', 'turbines.id = maintenance_interventions.turbine_id', 'left')
            ->join('users AS creator', 'creator.id = maintenance_interventions.created_by_user_id', 'left')
            ->join('users AS assignee', 'assignee.id = maintenance_interventions.assigned_to_user_id', 'left');
    }

    public function forOrganization(int $organizationId): array
    {
        return $this->withRelations()
            ->where('maintenance_interventions.organization_id', $organizationId)
            ->orderBy('maintenance_interventions.created_at', 'DESC')
            ->findAll();
    }
}
