<?php

use yii\db\Migration;

/**
 * Creates food_library table. user_id=NULL means global/shared food.
 * user_id=NOT NULL means nutritionist-specific private food item.
 */
class m240001_000008_create_food_library_table extends Migration
{
    public function safeUp(): void
    {
        $this->createTable('{{%food_library}}', [
            'id'          => $this->primaryKey()->unsigned()->comment('Primary key'),
            'user_id'     => $this->integer()->unsigned()->null()->comment('NULL=global, NOT NULL=nutritionist private food'),
            'name'        => $this->string(200)->notNull()->comment('Food name'),
            'category'    => $this->string(80)->null()->comment('e.g. Grains, Protein, Dairy, Vegetable, Fruit, Fat'),
            'tags'        => $this->string(500)->null()->comment('Comma-separated tags for search'),
            'serving_size'=> $this->string(50)->null()->defaultValue('100g')->comment('Default serving size'),
            'calories'    => $this->decimal(8, 2)->notNull()->defaultValue(0.00)->comment('kcal per serving'),
            'protein'     => $this->decimal(8, 2)->notNull()->defaultValue(0.00)->comment('grams protein per serving'),
            'carbs'       => $this->decimal(8, 2)->notNull()->defaultValue(0.00)->comment('grams carbohydrates per serving'),
            'fats'        => $this->decimal(8, 2)->notNull()->defaultValue(0.00)->comment('grams fats per serving'),
            'fiber'       => $this->decimal(8, 2)->notNull()->defaultValue(0.00)->comment('grams fiber per serving'),
            'is_active'   => $this->tinyInteger(1)->unsigned()->notNull()->defaultValue(1)->comment('1=active'),
            'created_at'  => $this->integer()->unsigned()->notNull()->comment('Unix timestamp'),
            'updated_at'  => $this->integer()->unsigned()->notNull()->comment('Unix timestamp'),
        ], 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT="Food nutrition library: global + nutritionist-specific"');

        // Composite index: show global (NULL user_id) + user-specific
        $this->createIndex('idx_food_user_name', '{{%food_library}}', ['user_id', 'name']);
        $this->createIndex('idx_food_category', '{{%food_library}}', 'category');
        $this->createIndex('idx_food_active', '{{%food_library}}', 'is_active');
    }

    public function safeDown(): void
    {
        $this->dropTable('{{%food_library}}');
    }
}
