import { v4 as uuidv4 } from 'uuid';

export default {
  up: async (queryInterface) => {
    const transaction = await queryInterface.sequelize.transaction();

    try {
      const now = new Date();

      const defaultConfigs = [
        {
          key: 'figma.api_timeout',
          value: JSON.stringify(30000),
          is_secret: false,
          scope: 'SYSTEM',
          scope_id: null
        },
        {
          key: 'storybook.default_port',
          value: JSON.stringify(6006),
          is_secret: false,
          scope: 'SYSTEM',
          scope_id: null
        },
        {
          key: 'rate_limit.requests_per_minute',
          value: JSON.stringify(60),
          is_secret: false,
          scope: 'SYSTEM',
          scope_id: null
        },
        {
          key: 'theme',
          value: JSON.stringify('auto'),
          is_secret: false,
          scope: 'SYSTEM',
          scope_id: null
        }
      ];

      const records = defaultConfigs.map(config => ({
        id: uuidv4(),
        ...config,
        schema_version: 1,
        created_at: now,
        updated_at: now
      }));

      await queryInterface.bulkInsert('config_settings', records, { transaction });

      await transaction.commit();
    } catch (err) {
      await transaction.rollback();
      console.error('Failed to seed default configs:', err);
      throw err;
    }
  },

  down: async (queryInterface) => {
    const transaction = await queryInterface.sequelize.transaction();
    try {
      await queryInterface.bulkDelete('config_settings', { scope: 'SYSTEM' }, { transaction });
      await transaction.commit();
    } catch (err) {
      await transaction.rollback();
      throw err;
    }
  }
};
