<?php
declare(strict_types=1);

use Migrations\BaseMigration;

class CreateCalendarEvents extends BaseMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * https://book.cakephp.org/migrations/4/en/migrations.html#the-change-method
     * @return void
     */
    public function change(): void
    {
        $signed = false;

        $table = $this->table('calendar_events', [
            'id' => false,
            'primary_key' => ['id'],
            'engine' => 'InnoDB',
            'collation' => 'utf8mb4_unicode_ci',
        ]);

        $table
            ->addColumn('id', 'biginteger', ['identity' => true, 'signed' => false])
            ->addColumn('user_id', 'integer', ['null' => true, 'signed' => $signed]) // 外键需与 logins.id 匹配
            ->addColumn('title', 'string', ['limit' => 200, 'null' => false])
            ->addColumn('description', 'text', ['null' => true])
            ->addColumn('start', 'datetime', ['null' => false])
            ->addColumn('end', 'datetime', ['null' => true])
            ->addColumn('all_day', 'boolean', ['default' => 0, 'null' => false])
            ->addColumn('location', 'string', ['limit' => 255, 'null' => true])
            ->addColumn('bg_color', 'string', ['limit' => 20, 'null' => true])
            ->addColumn('text_color', 'string', ['limit' => 20, 'null' => true])
            ->addColumn('status', 'string', ['limit' => 20, 'default' => 'confirmed', 'null' => false])
            ->addTimestamps('created', 'modified') // created/modified
            ->addIndex(['user_id'], ['name' => 'idx_calendar_events_user'])
            ->addIndex(['start'], ['name' => 'idx_calendar_events_start'])
            ->create();

        $this->table('calendar_events')
            ->addForeignKey('user_id', 'logins', 'id', [
                'delete'     => 'SET_NULL',
                'update'     => 'NO_ACTION',
                'constraint' => 'fk_calendar_events_user',
            ])
            ->update();
    }
}
