<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * `body` — the actual message text sent/recorded, distinct from
 * `provider_response` (a gateway's raw API reply). MessagingService
 * already computes this text at every call site (it's the $smsBody
 * parameter passed into send()); this just also persists it so the
 * Communication page can show what was actually said, not a JSON blob.
 * Nullable because rows written before this migration only have
 * provider_response — the view falls back to that for older rows rather
 * than showing a fabricated body.
 *
 * `sent_by` — the staff member who triggered a manual entry (a logged
 * call/note, or a manually-composed "Send New Message" SMS). Null means
 * "the system sent this automatically" (a booking confirmation, a
 * reminder, ...), which is the case for every row written before this
 * migration and for every automated send afterward too — this isn't
 * back-filled, since there's no way to know after the fact who (if
 * anyone) triggered an old automated send.
 */
class AddBodyAndSentByToMessageLog extends Migration
{
    public function up()
    {
        $this->forge->addColumn('message_log', [
            'body' => [
                'type' => 'TEXT',
                'null' => true,
                'after' => 'to_phone',
            ],
            'sent_by' => [
                'type'       => 'INT',
                'constraint' => 11,
                'unsigned'   => true,
                'null'       => true,
                'after'      => 'status',
            ],
        ]);

        $this->forge->addForeignKey('sent_by', 'users', 'id', '', 'SET NULL');
        $this->forge->processIndexes('message_log');
    }

    public function down()
    {
        $this->forge->dropForeignKey('message_log', 'message_log_sent_by_foreign');
        $this->forge->dropColumn('message_log', ['body', 'sent_by']);
    }
}
