<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * The stock-movement ledger CreateInventoryItemsTable's doc comment
 * deliberately left out at the time ("current stock levels only, no
 * movement ledger"). `inventory_items.quantity_in_stock` becomes a
 * maintained running total fed by this append-only ledger — the same
 * "denormalized total + immutable ledger" shape `folio_payments`
 * already uses for a folio's balance, not a novel pattern. Every write
 * goes through InventoryItemModel::receiveStock()/consumeStock()/
 * adjustStock(), which update both together in one transaction so they
 * can never drift.
 */
class CreateInventoryTransactionsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'inventory_item_id' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
            ],
            'type' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'comment'    => 'received|consumed|adjusted',
            ],
            'quantity' => [
                'type'       => 'INT',
                'comment'    => 'Signed — positive for received, negative for consumed, either for an adjustment.',
            ],
            'reference' => [
                'type'       => 'VARCHAR',
                'constraint' => 150,
                'null'       => true,
                'comment'    => 'Free text — supplier/invoice # for a receipt, reason for an adjustment, department for consumption.',
            ],
            'created_by' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'null'       => true,
            ],
            'created_at' => [
                'type' => 'DATETIME',
            ],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->addKey('inventory_item_id');
        $this->forge->addForeignKey('inventory_item_id', 'inventory_items', 'id', '', 'CASCADE');
        $this->forge->addForeignKey('created_by', 'users', 'id', '', 'SET NULL');
        $this->forge->createTable('inventory_transactions');
    }

    public function down()
    {
        $this->forge->dropTable('inventory_transactions', true);
    }
}
