<?php

namespace Tenant\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * The email counterpart to message_log (WhatsApp/SMS) — EmailService::
 * send() previously fired and forgot, with no record of what was sent to
 * whom. Same shape/reasoning as message_log: every attempt logged
 * regardless of outcome, so "did the guest actually get their invoice
 * emailed?" has a real answer. Feeds the per-guest communication
 * timeline on the guest profile (GuestController::show()) alongside
 * message_log and manually-logged calls/notes.
 */
class CreateEmailLogTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'guest_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
                'null'     => true,
            ],
            'to_email' => [
                'type'       => 'VARCHAR',
                'constraint' => 150,
            ],
            'subject' => [
                'type'       => 'VARCHAR',
                'constraint' => 200,
            ],
            'status' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'comment'    => 'sent, failed',
            ],
            'error' => [
                'type' => 'TEXT',
                'null' => true,
            ],
            'created_at' => [
                'type' => 'DATETIME',
            ],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey('guest_id');
        $this->forge->addForeignKey('guest_id', 'guests', 'id', '', 'SET NULL');
        $this->forge->createTable('email_log');
    }

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