<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

/**
 * Meter-based PM triggers on pm_schedules.
 *
 *   trigger_type = 'calendar'       → existing behaviour (next_due_at)
 *   trigger_type = 'running_hours'  → generate a WO when
 *                                      latest plant_readings.value_number
 *                                      >= last_meter_reading + meter_interval
 *   trigger_type = 'reading_value'  → same, but for any parameter_key
 *
 * Distinction: 'running_hours' is a convention meaning "meter_key defaults to
 * 'running_hours' and the interval is in hours." 'reading_value' lets an admin
 * point at any parameter (e.g. `flow_kg` every 10 000 kg).
 */
final class PmMeterTrigger extends AbstractMigration
{
    public function change(): void
    {
        $this->table('pm_schedules')
            ->addColumn('trigger_type', 'string', [
                'limit' => 20, 'default' => 'calendar', 'after' => 'is_active',
                'comment' => 'calendar | running_hours | reading_value',
            ])
            ->addColumn('meter_key', 'string', [
                'limit' => 60, 'null' => true, 'after' => 'trigger_type',
                'comment' => 'plant_readings.parameter_key to watch',
            ])
            ->addColumn('meter_interval', 'decimal', [
                'precision' => 14, 'scale' => 3, 'null' => true, 'after' => 'meter_key',
                'comment' => 'Units between PMs (hours / kg / cycles)',
            ])
            ->addColumn('last_meter_reading', 'decimal', [
                'precision' => 14, 'scale' => 3, 'null' => true, 'after' => 'meter_interval',
                'comment' => 'Meter value at last generation; next fires at + meter_interval',
            ])
            ->addIndex(['tenant_id', 'trigger_type'])
            ->update();
    }
}
