<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

/**
 * Control DB. Line items for a platform `invoices` row (e.g. "Growth
 * plan — Aug 2026", "Pro-rated upgrade credit"). Kept separate from
 * `invoices` the same way folio_line_items is separate from folios —
 * an invoice's `amount` is the sum of its line items, computed at
 * generation time and stored (not recomputed on every read).
 */
class CreateInvoiceLineItemsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => [
                'type'           => 'INT',
                'constraint'     => 11,
                'unsigned'       => true,
                'auto_increment' => true,
            ],
            'invoice_id' => [
                'type'     => 'INT',
                'constraint' => 11,
                'unsigned' => true,
            ],
            'description' => [
                'type'       => 'VARCHAR',
                'constraint' => 255,
            ],
            'amount' => [
                'type'       => 'DECIMAL',
                'constraint' => '10,2',
            ],
            'created_at' => [
                'type' => 'DATETIME',
                'null' => true,
            ],
        ]);

        $this->forge->addKey('id', true);
        $this->forge->addKey('invoice_id');
        $this->forge->addForeignKey('invoice_id', 'invoices', 'id', '', 'CASCADE');
        $this->forge->createTable('invoice_line_items');
    }

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