<?php

/**
 * @file
 * Install and schema hooks for taxa_laborum module.
 */

/**
 * Implements hook_schema().
 */
function taxa_laborum_schema() {
  $schema = [];

  // ===== TABLE 1: INGREDIENT USAGE TRACKING =====
  $schema['taxa_laborum_ingredient_usage'] = [
    'description' => 'Stores taxa_laborum ingredient usage for reporting',
    'fields' => [
      'id' => [
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary Key',
      ],
      'timestamp' => [
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Time when calculation was performed',
      ],
      'user_id' => [
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'User ID who performed calculation',
      ],
      'ingredient_id' => [
        'type' => 'int',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Taxonomy term ID of the ingredient',
      ],
      'ingredient_name' => [
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Name of the ingredient',
      ],
      'quantity' => [
        'type' => 'float',
        'size' => 'normal',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Amount of ingredient used',
      ],
      'unit_price' => [
        'type' => 'float',
        'size' => 'normal',
        'not null' => TRUE,
        'default' => 0,
        'description' => 'Unit price of ingredient at time of calculation',
      ],
      'calculation_id' => [
        'type' => 'varchar',
        'length' => 64,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Unique ID for this calculation',
      ],
    ],
    'primary key' => ['id'],
    'indexes' => [
      'timestamp' => ['timestamp'],
      'ingredient_id' => ['ingredient_id'],
      'calculation_id' => ['calculation_id'],
    ],
  ];

  // ===== TABLE 2: RECIPE STORAGE (SHARED ACCESS) =====
  $schema['taxa_laborum_recipe_storage'] = [
    'description' => 'Stores taxa_laborum recipes - shared across authenticated users',
    'fields' => [
      'recipe_id' => [
        'type' => 'serial',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'Primary key',
      ],
      'recipe_name' => [
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'description' => 'Recipe name (e.g., "Cough Drops")',
      ],
      'ingredients_data' => [
        'type' => 'text',
        'size' => 'big',
        'not null' => TRUE,
        'description' => 'JSON-serialized array of ingredients',
      ],
      'created_by_user_id' => [
        'type' => 'int',
        'unsigned' => TRUE,
        'not null' => TRUE,
        'description' => 'User ID who created the recipe (audit trail)',
      ],
      'created_timestamp' => [
        'type' => 'int',
        'not null' => TRUE,
        'description' => 'Recipe creation timestamp',
      ],
      'updated_by_user_id' => [
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'User ID who last updated the recipe',
      ],
      'updated_timestamp' => [
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'Last modification timestamp',
      ],
      'deleted_by_user_id' => [
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'User ID who deleted the recipe (audit)',
      ],
      'deleted_timestamp' => [
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'Recipe deletion timestamp',
      ],
      'is_active' => [
        'type' => 'int',
        'size' => 'tiny',
        'default' => 1,
        'not null' => TRUE,
        'description' => 'Soft delete flag (1 = active, 0 = deleted)',
      ],
    ],
    'primary key' => ['recipe_id'],
    'indexes' => [
      'recipe_name_idx' => ['recipe_name'],
      'is_active_idx' => ['is_active'],
      'created_timestamp_idx' => ['created_timestamp'],
      'created_by_user_id_idx' => ['created_by_user_id'],
    ],
    'unique keys' => [
      'recipe_name_unique' => ['recipe_name'],
    ],
  ];

  return $schema;
}

/**
 * Implements hook_install().
 */
function taxa_laborum_install() {
  \Drupal::messenger()->addStatus(
    t('Taxa Laborum module installed successfully. Database tables created.')
  );
}

/**
 * Update 9001: Create taxa_laborum_ingredient_usage table.
 */
function taxa_laborum_update_9001() {
  $schema = \Drupal::database()->schema();

  if (!$schema->tableExists('taxa_laborum_ingredient_usage')) {
    $definition = taxa_laborum_schema();
    $schema->createTable(
      'taxa_laborum_ingredient_usage',
      $definition['taxa_laborum_ingredient_usage']
    );
    return t('? Created taxa_laborum_ingredient_usage table for tracking ingredient usage.');
  }

  return t('?? The taxa_laborum_ingredient_usage table already exists. No changes were made.');
}

/**
 * Update 9002: Create taxa_laborum_recipe_storage table with shared access.
 */
function taxa_laborum_update_9002() {
  $schema = \Drupal::database()->schema();

  if (!$schema->tableExists('taxa_laborum_recipe_storage')) {
    $definition = taxa_laborum_schema();
    $schema->createTable('taxa_laborum_recipe_storage', $definition['taxa_laborum_recipe_storage']);
    return t('? Created taxa_laborum_recipe_storage table for shared recipe management.');
  }

  return t('?? The taxa_laborum_recipe_storage table already exists. No changes were made.');
}

/**
 * Update 9003: Migrate from user-specific to shared recipes (if upgrading).
 */
function taxa_laborum_update_9003() {
  $schema = \Drupal::database()->schema();
  
  if ($schema->tableExists('taxa_laborum_recipe_storage')) {
    // Add audit columns if upgrading
    if (!$schema->fieldExists('taxa_laborum_recipe_storage', 'updated_by_user_id')) {
      $schema->addField('taxa_laborum_recipe_storage', 'updated_by_user_id', [
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'User ID who last updated the recipe',
      ]);
    }

    if (!$schema->fieldExists('taxa_laborum_recipe_storage', 'deleted_by_user_id')) {
      $schema->addField('taxa_laborum_recipe_storage', 'deleted_by_user_id', [
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'User ID who deleted the recipe',
      ]);
    }

    if (!$schema->fieldExists('taxa_laborum_recipe_storage', 'deleted_timestamp')) {
      $schema->addField('taxa_laborum_recipe_storage', 'deleted_timestamp', [
        'type' => 'int',
        'unsigned' => TRUE,
        'description' => 'Recipe deletion timestamp',
      ]);
    }

    return t('? Migrated taxa_laborum_recipe_storage to shared access model with audit columns.');
  }

  return t('?? Table does not exist or already migrated.');
}

/**
 * Implements hook_uninstall().
 */
function taxa_laborum_uninstall() {
  $schema = \Drupal::database()->schema();

  if ($schema->tableExists('taxa_laborum_ingredient_usage')) {
    $schema->dropTable('taxa_laborum_ingredient_usage');
  }

  if ($schema->tableExists('taxa_laborum_recipe_storage')) {
    $schema->dropTable('taxa_laborum_recipe_storage');
  }

  \Drupal::messenger()->addStatus(
    t('Taxa Laborum module uninstalled. Database tables removed.')
  );
}