import { MigrationInterface, QueryRunner, Table, TableIndex } from 'typeorm';

export class CreateSettingsTable1735000000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    // Create settings table
    await queryRunner.createTable(
      new Table({
        name: 'settings',
        columns: [
          {
            name: 'id',
            type: 'uuid',
            isPrimary: true,
            generationStrategy: 'uuid',
            default: 'uuid_generate_v4()',
          },
          {
            name: 'key',
            type: 'varchar',
            length: '100',
            isUnique: true,
          },
          {
            name: 'value',
            type: 'text',
          },
          {
            name: 'description',
            type: 'text',
            isNullable: true,
          },
          {
            name: 'type',
            type: 'varchar',
            length: '50',
            default: "'string'",
          },
          {
            name: 'created_at',
            type: 'timestamptz',
            default: 'CURRENT_TIMESTAMP',
          },
          {
            name: 'updated_at',
            type: 'timestamptz',
            default: 'CURRENT_TIMESTAMP',
          },
        ],
      }),
      true,
    );

    // Create index on key for faster lookups
    await queryRunner.createIndex(
      'settings',
      new TableIndex({
        name: 'IDX_SETTINGS_KEY',
        columnNames: ['key'],
      }),
    );

    // Insert default settings
    await queryRunner.query(`
      INSERT INTO settings (key, value, description, type) VALUES
        ('registration_mode', 'public', 'Registration mode: public or invite_only', 'string'),
        ('require_invite_code', 'false', 'Whether invite codes are required for registration', 'boolean'),
        ('max_family_size', '10', 'Maximum number of members allowed in a family', 'number'),
        ('max_children_per_family', '10', 'Maximum number of children allowed per family', 'number'),
        ('enable_ai_features', 'true', 'Enable AI assistant features', 'boolean'),
        ('enable_voice_input', 'true', 'Enable voice input for activity tracking', 'boolean')
      ON CONFLICT (key) DO NOTHING;
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Drop index
    await queryRunner.dropIndex('settings', 'IDX_SETTINGS_KEY');

    // Drop table
    await queryRunner.dropTable('settings');
  }
}
