<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

/**
 * assets:
 *   - Every asset belongs to a tenant and a site.
 *   - Every asset has a type (Generator, Chiller, ...) — determines the meta_json schema.
 *   - parent_asset_id lets you nest components (bearing under alternator under generator).
 *   - meta_json holds the per-type dynamic fields defined in asset_type_fields.
 *   - Status is a coarse lifecycle: active | inactive | scrapped | in_transit
 */
final class CreateAssets extends AbstractMigration
{
    public function change(): void
    {
        $this->table('assets', ['id' => 'asset_id', 'signed' => false])
            ->addColumn('tenant_id',       'integer', ['signed' => false])
            ->addColumn('site_id',         'integer', ['null' => true, 'signed' => false])
            ->addColumn('asset_type_id',   'integer', ['signed' => false])
            ->addColumn('parent_asset_id', 'integer', ['null' => true, 'signed' => false])
            ->addColumn('code',            'string',  ['limit' => 60,  'null' => true])
            ->addColumn('name',            'string',  ['limit' => 160])
            ->addColumn('serial_number',   'string',  ['limit' => 100, 'null' => true])
            ->addColumn('asset_tag',       'string',  ['limit' => 60,  'null' => true])
            ->addColumn('meta_json',       'json',    ['null' => true])
            ->addColumn('notes',           'text',    ['null' => true])
            ->addColumn('status',          'string',  ['limit' => 20, 'default' => 'active'])
            ->addColumn('installed_at',    'date',    ['null' => true])
            ->addColumn('created_by',      'integer', ['null' => true, 'signed' => false])
            ->addColumn('created_at',      'datetime',['default' => 'CURRENT_TIMESTAMP'])
            ->addColumn('updated_at',      'datetime',['default' => 'CURRENT_TIMESTAMP', 'update' => 'CURRENT_TIMESTAMP'])
            ->addColumn('deleted_at',      'datetime',['null' => true])
            ->addIndex(['tenant_id', 'status'])
            ->addIndex(['tenant_id', 'site_id'])
            ->addIndex(['tenant_id', 'asset_type_id'])
            ->addIndex(['tenant_id', 'name'])
            ->addIndex(['tenant_id', 'serial_number'])
            ->addIndex(['parent_asset_id'])
            ->addForeignKey('tenant_id',       'tenants',     'tenant_id',     ['delete' => 'RESTRICT', 'update' => 'CASCADE'])
            ->addForeignKey('site_id',         'sites',       'site_id',       ['delete' => 'SET_NULL', 'update' => 'CASCADE'])
            ->addForeignKey('asset_type_id',   'asset_types', 'asset_type_id', ['delete' => 'RESTRICT', 'update' => 'CASCADE'])
            ->addForeignKey('parent_asset_id', 'assets',      'asset_id',      ['delete' => 'SET_NULL', 'update' => 'CASCADE'])
            ->addForeignKey('created_by',      'users',       'user_id',       ['delete' => 'SET_NULL', 'update' => 'CASCADE'])
            ->create();
    }
}
