<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

/**
 * ISO 14224-ish failure taxonomy + downtime capture on incidents.
 *   failure_codes: mode / mechanism / cause tuple, tenant-scoped
 *   incidents: failure_code_id, downtime_minutes
 * The tuple is deliberately kept as a single row (not three separate lookups) —
 * simpler UX, and the classic RCA reports can group by any of the three columns.
 */
final class FailureCodesAndDowntime extends AbstractMigration
{
    public function change(): void
    {
        $this->table('failure_codes', ['id' => 'failure_code_id', 'signed' => false])
            ->addColumn('tenant_id', 'integer', ['signed' => false])
            ->addColumn('code',      'string',  ['limit' => 40])
            ->addColumn('mode',      'string',  ['limit' => 80])
            ->addColumn('mechanism', 'string',  ['limit' => 80])
            ->addColumn('cause',     'string',  ['limit' => 80])
            ->addColumn('description','string', ['limit' => 200, 'null' => true])
            ->addColumn('created_at','datetime',['default' => 'CURRENT_TIMESTAMP'])
            ->addIndex(['tenant_id', 'code'], ['unique' => true])
            ->addIndex(['tenant_id', 'mode'])
            ->addForeignKey('tenant_id', 'tenants', 'tenant_id', ['delete' => 'CASCADE', 'update' => 'CASCADE'])
            ->create();

        $this->table('incidents')
            ->addColumn('failure_code_id',  'integer', ['null' => true, 'signed' => false, 'after' => 'incident_type_id'])
            ->addColumn('downtime_minutes', 'integer', ['null' => true, 'signed' => false, 'after' => 'end_at'])
            ->addForeignKey('failure_code_id', 'failure_codes', 'failure_code_id', ['delete' => 'SET_NULL', 'update' => 'CASCADE'])
            ->update();

        // Seed a plant-oriented starter set for the primary tenant.
        $tenantId = (int) ($this->fetchRow(
            "SELECT tenant_id FROM tenants WHERE subdomain = 'orchid' LIMIT 1"
        )['tenant_id'] ?? 0);

        if ($tenantId > 0) {
            $starter = [
                // code,             mode,                 mechanism,          cause,               description
                ['ELE-01', 'Fails to start',     'Electrical',       'Blown fuse',        'Fuse or breaker tripped, no start'],
                ['ELE-02', 'Low voltage',        'Electrical',       'Wiring loose',      'Loose or corroded connection'],
                ['ELE-03', 'Overheating',        'Electrical',       'Overload',          'Sustained overload / undersized wiring'],
                ['MEC-01', 'Vibration',          'Mechanical',       'Bearing wear',      'Excessive vibration from worn bearings'],
                ['MEC-02', 'Leak',               'Sealing',          'Gasket failure',    'Fluid leak from gasket / o-ring'],
                ['MEC-03', 'Alignment drift',    'Mechanical',       'Loose coupling',    'Shaft coupling drift / misalignment'],
                ['HYD-01', 'Pressure loss',      'Hydraulic',        'Pump wear',         'Loss of pressure — worn pump internals'],
                ['LUB-01', 'Low oil',            'Lubrication',      'Human error',       'Missed top-up / operator neglect'],
                ['LUB-02', 'Oil contamination',  'Lubrication',      'Ingress',           'Water/dirt ingress into oil circuit'],
                ['COL-01', 'Coolant loss',       'Cooling',          'Hose failure',      'Coolant hose split / clamp failure'],
                ['INS-01', 'Instrument drift',   'Instrumentation',  'Calibration lapse', 'Sensor reading drifted out of tolerance'],
                ['HUM-01', 'Operator error',     'Human',            'Training gap',      'Wrong procedure / knowledge gap'],
                ['ENV-01', 'Weather damage',     'External',         'Environmental',     'Storm / lightning damage'],
                ['UTL-01', 'Utility loss',       'External',         'Grid outage',       'Loss of external power/fuel supply'],
            ];
            foreach ($starter as $r) {
                $this->table('failure_codes')->insert([
                    'tenant_id'   => $tenantId,
                    'code'        => $r[0],
                    'mode'        => $r[1],
                    'mechanism'   => $r[2],
                    'cause'       => $r[3],
                    'description' => $r[4],
                ])->saveData();
            }
        }
    }
}
