<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Control DB. Tenant ↔ plan assignment + lifecycle. Multiple rows per
 * tenant accumulate over time (upgrade, downgrade, renewal) rather than
 * updating one row in place, so billing history stays intact — the same
 * "never rewrite history" reasoning used for rate plans and folio
 * charges. SubscriptionModel::currentFor() is the only place that should
 * decide "which row is the active one" (most recent by id).
 */
class CreateSubscriptionsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'tenant_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
            ],
            'plan_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
            ],
            'status' => [
                'type'       => 'VARCHAR',
                'constraint' => 20,
                'default'    => 'trial',
                'comment'    => 'trial|active|past_due|cancelled — validated against Config\Lookups.',
            ],
            'trial_ends_at' => [
                'type' => 'DATETIME',
                'null' => true,
            ],
            'current_period_start' => [
                'type' => 'DATE',
                'null' => true,
            ],
            'current_period_end' => [
                'type' => 'DATE',
                'null' => true,
            ],
            'cancelled_at' => [
                'type' => 'DATETIME',
                'null' => true,
            ],
            'created_at' => [
                'type' => 'DATETIME',
                'null' => true,
            ],
            'updated_at' => [
                'type' => 'DATETIME',
                'null' => true,
            ],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey('tenant_id');
        $this->forge->addForeignKey('tenant_id', 'tenants', 'id', '', 'CASCADE');
        $this->forge->addForeignKey('plan_id', 'plans', 'id', '', 'RESTRICT');
        $this->forge->createTable('subscriptions');
    }

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