<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

/**
 * Polymorphic attachment table — one row per file, referencing any owner type.
 * owner_type is a string ('asset','incident','work_order','expense',...) so we
 * can add new owner kinds without a migration.
 */
final class CreateAttachments extends AbstractMigration
{
    public function change(): void
    {
        $this->table('attachments', ['id' => 'attachment_id', 'signed' => false])
            ->addColumn('tenant_id',     'integer', ['signed' => false])
            ->addColumn('owner_type',    'string',  ['limit' => 40]) // asset|incident|work_order|expense
            ->addColumn('owner_id',      'integer', ['signed' => false])
            ->addColumn('file_name',     'string',  ['limit' => 255])
            ->addColumn('original_name', 'string',  ['limit' => 255])
            ->addColumn('file_ext',      'string',  ['limit' => 20,  'null' => true])
            ->addColumn('mime_type',     'string',  ['limit' => 120, 'null' => true])
            ->addColumn('size_bytes',    'integer', ['null' => true])
            ->addColumn('caption',       'string',  ['limit' => 255, 'null' => true])
            ->addColumn('uploaded_by',   'integer', ['null' => true, 'signed' => false])
            ->addColumn('created_at',    'datetime',['default' => 'CURRENT_TIMESTAMP'])
            ->addColumn('deleted_at',    'datetime',['null' => true])
            ->addIndex(['tenant_id', 'owner_type', 'owner_id'])
            ->addIndex(['owner_type', 'owner_id'])
            ->addForeignKey('tenant_id',   'tenants', 'tenant_id', ['delete' => 'RESTRICT', 'update' => 'CASCADE'])
            ->addForeignKey('uploaded_by', 'users',   'user_id',   ['delete' => 'SET_NULL', 'update' => 'CASCADE'])
            ->create();
    }
}
